...
A similar situation arises when realloc()
is supplied a pointer to non-dynamically nondynamically allocated memory. The realloc()
function is used to resize a block of dynamic memory. If realloc()
is supplied a pointer to memory not allocated by a memory allocation function, such as malloc()
, the program may terminate abnormally.
...
Code Block | ||
---|---|---|
| ||
enum { MAX_ALLOCATION = 1000 }; int main(int argc, const char *argv[]) { char *str = NULL; size_t len; if (argc == 2) { len = strlen(argv[1])+1; if (len > MAX_ALLOCATION) { /* Handle Errorerror */ } str = (char *)malloc(len); if (str == NULL) { /* Handle Allocationallocation Errorerror */ } 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 modified to eliminate the possibility of str
referencing non-dynamic nondynamic memory when it is supplied to free()
.
Code Block | ||
---|---|---|
| ||
enum { MAX_ALLOCATION = 1000 }; int main(int argc, const char *argv[]) { char *str = NULL; size_t len; if (argc == 2) { len = strlen(argv[1])+1; if (len > MAX_ALLOCATION) { /* Handle Errorerror */ } str = (char *)malloc(len); if (str == NULL) { /* Handle Allocationallocation Errorerror */ } strcpy(str, argv[1]); } else { printf("%s\n", "usage: $>a.exe [string]"); return -1; } /* ... */ free(str); return 0; } |
...