To gain better understanding of malloc() and realloc() I'm trying to run the following code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
char *str;
str = malloc(20);
str = strcpy(str, "inf110_malloc_test");
printf("String = %s, Address = %u\n", str, str);
str = realloc(str, 25);
str = strcat(str, " is dene perfectly.");
printf("String = %s Address = %u\n", str, str);
free(str);
return(0);
}
Output:
String = inf110_malloc_test, Address = 1840192
String = inf110_malloc_test is dene perfectly. Address = 1840192
The problem is that the code is running just fine even if I pass NULL
argument to malloc()
.
...
str = malloc(NULL);
...
I read on cplusplus.com the following:
To avoid overflows, the size of the array pointed by destination shall be long enough to contain the same C string as source (including the terminating null character), and should not overlap in memory with source.
Why the program doesn't crash at this point? Do strcpy()
allocate some enough memory automatically?