...
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 also terminate abnormally.
...
The following piece of code validates the number of command line arguemnts. If the correct number of commmand line arguements arguments have been specified, memory is allocated with malloc()
and referenced by str
. 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 freed.
...
Code Block |
---|
int main(int argc, char *argv[]) {
char *str = NULL;
if (argc == 2) {
str = malloc(strlen(argv[1]));
if (str == NULL) {
/* Handle Allocation Error */
}
strcpy(str, argv[1]);
}
else {
printf("usage: $>a.exe [string]\n");
return 1;
}
/* ... */
free(str);
return 0;
}
|
...