...
Noncompliant Code Example
C99 includes The C standard includes support for variable-length arrays (VLAs) [ISO/IEC 9899:19992011]. If the array length is derived from an untrusted data source, an attacker can cause the process to perform an excessive allocation on the stack.
...
Code Block | ||||
---|---|---|---|---|
| ||||
int copy_file(FILE *src, FILE *dst, size_t bufsize) {
char buf[bufsize];
while (fgets(buf, bufsize, src)) {
if (fputs(buf, dst) == EOF) {
/* Handle error */
}
}
return 0;
}
|
...
Code Block | ||||
---|---|---|---|---|
| ||||
int copy_file(FILE *src, FILE *dst, size_t bufsize) {
if (bufsize == 0) {
/* Handle error */
}
char *buf = (char *)malloc(bufsize);
if (!buf) {
return -1;
}
while (fgets(buf, bufsize, src)) {
if (fputs(buf, dst) == EOF) {
/* Handle error */
}
}
/* ... */
free(buf);
return 0;
}
|
...
Code Block | ||||
---|---|---|---|---|
| ||||
unsigned long fib1(unsigned int n) {
if (n == 0) {
return 0;
}
else if (n == 1 || n == 2) {
return 1;
}
else {
return fib1(n-1) + fib1(n-2);
}
}
|
...
Code Block | ||||
---|---|---|---|---|
| ||||
unsigned long fib2(unsigned int n) {
if (n == 0) {
return 0;
}
else if (n == 1 || n == 2) {
return 1;
}
unsigned long prev = 1;
unsigned long cur = 1;
unsigned int i;
for (i = 3; i <= n; i++) {
unsigned long tmp = cur;
cur = cur + prev;
prev = tmp;
}
return cur;
}
|
...
Tool | Version | Checker | Description | |||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Section | |
| Section | STACK_USE | Section | Can help detect single stack allocations that are dangerously large, although it will not detect excessive stack use resulting from recursion. |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...
CERT C++ Secure Coding Standard: MEM05-CPP. Avoid large stack allocations
ISO/IEC 9899:19992011 Section 6.7.56.2, "Array Declaratorsdeclarators," , and Section 7.2022.3, "Memory management functions"
...
[Loosemore 2007] Section 3.2.5, "Automatic Storage storage with Variable Sizevariable sze"
[Seacord 2005a] Chapter 4, "Dynamic Memory Management"
[van Sprundel 2006] "Stack Overflowoverflow"
...