CodeQL documentation

Call to alloca in a loop

ID: cpp/alloca-in-loop
Kind: problem
Security severity: 7.5
Severity: warning
Precision: high
Tags:
   - reliability
   - correctness
   - security
   - external/cwe/cwe-770
Query suites:
   - cpp-code-scanning.qls
   - cpp-security-extended.qls
   - cpp-security-and-quality.qls

Click to see the query in the CodeQL repository

The alloca macro allocates memory by expanding the current stack frame. Invoking alloca within a loop may lead to a stack overflow because the memory is not released until the function returns.

Recommendation

Consider invoking alloca once outside the loop, or using malloc or new to allocate memory on the heap if the allocation must be done inside the loop.

Example

The variable path is allocated inside a loop with alloca. Consequently, storage for all copies of the path is present in the stack frame until the end of the function.

char *dir_path;
char **dir_entries;
int count;

for (int i = 0; i < count; i++) {
  char *path = (char*)alloca(strlen(dir_path) + strlen(dir_entry[i]) + 2);
  // use path
}

In the revised example, path is allocated with malloc and freed at the end of the loop.

char *dir_path;
char **dir_entries;
int count;

for (int i = 0; i < count; i++) {
  char *path = (char*)malloc(strlen(dir_path) + strlen(dir_entry[i]) + 2);
  // use path
  free(path);
}

References

  • © GitHub, Inc.
  • Terms
  • Privacy
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy