...
Non-Compliant Code Example (argument validation)
Using a user-defined functions function to calculate the amount of memory to allocate is a common practice that may sometimes be necessary. However, if the function used to calculate the size parameter is flawed, then an incorrect size argument will be supplied to the allocation routine.
...
Code Block | ||
---|---|---|
| ||
#include <stdlib.h> #include <stdio.h> enum { MAXLINE = 1000 }; size_t calc() { char line[MAXLINE], c; size_t size = 0; while ( (c = getchar()) != EOF && c != '\n') { line[size] = c; size++; if (size >= MAXLINE) break; } return size; } int main(void) { char * line = malloc(calc()); printf("%d\n", size/* ... */ free(line); } |
Wiki Markup |
---|
However, if no characters are entered, {{calc()}} will return {{0}}. Because there is no validation on the result of {{calc()}}, a {{malloc(0)}} \[[MEM04-A. Do not make assumptions about the result of allocating 0 bytes]\] could occur, which could lead to a buffer overflow. |
...
Code Block | ||
---|---|---|
| ||
#include <stdlib.h> #include <stdio.h> enum { MAXLINE = 1000 }; size_t calc() { char line[MAXLINE], c; size_t size = 0; while ( (c = getchar()) != EOF && c != '\n') { line[size] = c; size++; if (size >= MAXLINE) break; } return size; } int main(void) { size_t size = calc(); if (!size > 0) {) { /* Handle invalid size */ } char * line = malloc(size) /* printf("%d\n", size); }... */ free(line); } |
Risk Assessment
Calling a function with incorrect arguments can result in unexpected or unintended program behavior.
...