Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Call to alloca in a loop

ID: cpp/alloca-in-loopKind: problemSecurity severity: 7.5Severity: warningPrecision: highTags:   - reliability   - correctness   - security   - external/cwe/cwe-770Query suites:   - cpp-code-scanning.qls   - cpp-security-extended.qls   - cpp-security-and-quality.qls

Click to see the query in the CodeQL repository

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

Recommendation

Consider invokingalloca once outside the loop, or usingmalloc ornew to allocate memory on the heap if the allocation must be done inside the loop.

Example

The variablepath is allocated inside a loop withalloca. 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;intcount;for(inti=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 withmalloc and freed at the end of the loop.

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

References


[8]ページ先頭

©2009-2025 Movatter.jp