...
Non-Compliant Code Example
This piece of code validates the number of command line arguments. If the correct number of commmand line arguments have been specified, the requested amount of memory is validated to ensure that it is an acceptable size, and the memory is allocated with malloc()
. Next, the second command line argument is copied into str
for further processing. Once this processing is complete, str
is freed. However, if the incorrect number of arguments have been specified, str
is set to a string literal and printed. Because str
now references memory that was not dynamically allocated, an error will occur when str
memory is freednon-compliant code example sets str
to reference either dynamically allocated memory or a statically allocated string literal depending on the value of argc
. In either case, str} is passed as an argument to {{free()
. If anything other than dynamic allocated memory is referenced by str
, the call to free(str)
is erroneous.
Code Block | ||
---|---|---|
| ||
enum { MAX_ALLOCATION = 1000 }; int main(int argc, char *argv[]) { char *str = NULL; size_t len; if (argc == 2) { len = strlen(argv[1])+1; if (len > MAX_ALLOCATION) { /* Handle Error */ } str = malloc(len); if (str == NULL) { /* Handle Allocation Error */ } strcpy(str, argv[1]); } else { str = "usage: $>a.exe [string]"; printf("%s\n", str); } /* ... */ free(str); return 0; } |
...
In the compliant solution, the program has been changed modified to eliminate the possibility of str
referencing non-dynamic memory when it is supplied to free()
.
...