...
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 Errorerror */
}
}
return 0;
}
|
Wiki Markup |
---|
The BSD extension function {{alloca()}} behaves in a similar fashion to VLAsvariable-length arrays; its use is not recommended \[[Loosemore 07|AA. C References#Loosemore 07]\] . |
Compliant Solution
This compliant solution replaces the variable-length array with a call to malloc()
. If malloc()
fails, the return value can be checked to prevent the program from terminating abnormally.
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 Errorerror */
}
}
/* ... */
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);
}
}
|
The required stack space needed grows exponentially with respect to the parameter n
. Large values of n
have been shown to cause abnormal program termination.
...
Wiki Markup |
---|
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.7.5.2, "Array declarators", and Section 7.20.3, "Memory management functions"
\[[ISO/IEC PDTR 24772|AA. C References#ISO/IEC PDTR 24772]\] "GDL Recursion"
\[[Loosemore 07|AA. C References#Loosemore 07]\] [Section 3.2.5, "Automatic Storage with Variable Size"|http://www.gnu.org/software/libc/manual/html_mono/libc.html#Variable-Size-Automatic]
\[[MISRA 04|AA. C References#MISRA 04]\] Rule 16.2
\[[Seacord 05a|AA. C References#Seacord 05]\] Chapter 4, "Dynamic Memory Management"
\[[van Sprundel 06|http://ilja.netric.org/files/Unusual%20bugs.pdf]\] "Stack Overflow" |
...