CodeQL 文档

循环中调用 alloca

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

点击查看 CodeQL 存储库中的查询

alloca 宏通过扩展当前堆栈帧来分配内存。在循环中调用 alloca 可能导致堆栈溢出,因为在函数返回之前不会释放内存。

建议

考虑在循环外调用一次 alloca,或者如果必须在循环中分配内存,请使用 mallocnew 在堆上分配内存。

示例

变量 path 使用 alloca 在循环中分配。因此,在函数结束之前,所有 path 副本的存储空间都存在于堆栈帧中。

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
}

在修改后的示例中,path 使用 malloc 分配,并在循环结束时释放。

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);
}

参考资料

  • ©GitHub, Inc.
  • 条款
  • 隐私