I saw that you need to use malloc before but I don't understand if you MUST use it
If you need to use malloc
before you can realloc
something, then by definition you must only realloc
things originally allocated with malloc
.
You're trying to find some space between "need" and "must" that doesn't exist.
... for some reason the program crushes on the realloc
You already said you know you need to use malloc
. Then you didn't use malloc
, and you're asking why this is a problem. You could at least try doing the thing you "know" you need to do, to see if that solves the problem.
The program should probably look like
int main()
{
/* array is an automatic local variable. It wasn't dynamically allocated
in the first place, so can't be dynamically re-allocated either.
You cannot (and don't need to) free it either, it just goes out of scope
like any other automatic variable.
*/
char array[] = "fun";
/* you need to use malloc (or one of the other dynamic allocation functions)
before you can realloc, as you said yourself */
char *dynamic = malloc(1+strlen(array));
memcpy(dynamic, array, 1+strlen(array));
/* realloc can move your data, so you must use the returned address */
dynamic = str_func(dynamic);
printf("old:'%s', new:'%s'\n", array, dynamic);
/* not really essential since the program is about to exit anyway */
free(dynamic);
}
char* str_func(char* str)
{
char* newstr = realloc(str, strlen(str) + 2);
if (newstr) {
strcat(newstr, "p");
return newstr;
} else {
/* we failed to make str larger, but it is still there and should be freed */
return str;
}
}
Your original condition isn't quite correct: actually the pointer passed to realloc
... must be previously allocated by malloc()
, calloc()
or realloc()
and not yet freed with a call to free or realloc
[OR] If ptr is NULL, the behavior is the same as calling malloc(new_size)
.