为指针类型数组分配的内存不足¶
ID: cpp/suspicious-allocation-size
Kind: problem
Security severity: 8.1
Severity: warning
Precision: medium
Tags:
- reliability
- security
- external/cwe/cwe-131
- external/cwe/cwe-122
Query suites:
- cpp-security-extended.qls
- cpp-security-and-quality.qls
使用 malloc
、calloc
或 realloc
从内存中分配数组时,应确保分配的内存足以容纳所需指针类型的倍数。分配给非 void 指针变量的调用,但分配的内存不足,将在指针上的字段访问指向超出分配数组的内存时导致缓冲区溢出。缓冲区溢出可能导致从分段错误到安全漏洞的各种问题。
建议¶
突出显示的调用分配的内存不是指针类型的倍数,这会导致内存溢出。使用 sizeof
运算符来确保函数调用为该类型分配了足够的内存。
示例¶
#define RECORD_SIZE 30 //incorrect or outdated size for record
typedef struct {
char name[30];
int status;
} Record;
void f() {
Record* p = malloc(RECORD_SIZE * 4); //wrong: not a multiple of the size of Record
p[3].status = 1; //will most likely segfault
...
}