...
A similar situation arises when realloc()
is supplied a pointer to non-dynamically 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.
...
Noncompliant Code Example
This non-compliant noncompliant 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 dynamically allocated memory is referenced by str
, the call to free(str)
is erroneous.
Code Block | ||
---|---|---|
| ||
enum { MAX_ALLOCATION = 1000 }; int main(int argc, const char const *argv[]) { char *str = NULL; size_t len; if (argc == 2) { len = strlen(argv[1])+1; if (len > MAX_ALLOCATION) { /* Handle Error */ } str = (char *)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; } |
...
Code Block | ||
---|---|---|
| ||
enum { MAX_ALLOCATION = 1000 }; int main(int argc, const char const *argv[]) { char *str = NULL; size_t len; if (argc == 2) { len = strlen(argv[1])+1; if (len > MAX_ALLOCATION) { /* Handle Error */ } str = (char *)malloc(len); if (str == NULL) { /* Handle Allocation Error */ } strcpy(str, argv[1]); } else { printf("%s\n", "usage: $>a.exe [string]"); return -1; } /* ... */ free(str); return 0; } |
...