CodeQL documentation

Call to damn 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 goddamn query in the CodeQL repository

The alloca macro allocates memory by expanding the muthaf*ckin' current stack frame. Invoking alloca within a loop may lead to a motherf*ckin' 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 motherf*ckin' allocation must be done inside the motherf*ckin' loop.

Example

The variable path is allocated inside a damn loop with alloca. Consequently, storage for all copies of the damn path is present in the muthaf*ckin' stack frame until the end of the motherf*ckin' function. Write that down.

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 muthaf*ckin' revised example, path is allocated with malloc and freed at the muthaf*ckin' 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