Suppose I have a char pointer which points to some string in memory.
and suppose I want to copy that string to some other place in memory.
void cpy(char **dst, char *src)
{
*dst = (char *) realloc(*dst, strlen(src) + 1);
memcpy(*dst, src, strlen(src) + 1);
}
(Assume memory allocation is successful, and src is not NULL)
What if I call this function like this:
char *str = malloc(14);
memcpy(str,"hello, world!", 14);
cpy(&str,str+7);
Now I would expect srt to point to the string "world!" (Which it does in my tests).
But what concerns me is that in this call to cpy, *dst and src actually point to different locations of the same string. And, when calling realloc on *dst, it’s possible that this memory will be freed. But in the next line I’m trying to copy from that place with memcpy.
So the questions is: Is there something wrong with it?
Or to put it another way – is it okay to free memory, and use it immediately afterwards?
Thanks.
Note: The example was updated so that realloc is called on memory that was obtained with malloc.
Everything is wrong with this. It is outright undefined behaviour to call
reallocon a pointer that was not obtained withmallocetc.As @Daniel Fischer points out, it is also undefined behaviour to use
memcpyon overlapping regions of memory (in which case you should usememmove), so you have to be careful.Update: After your substantial edit, the question is quite different. It is now equivalent to this condensed version:
This is also undefined behaviour, because you are not allowed to access the memory pointed to by
sanymore after a successfulrealloc, and you’re not allowed to access the memory pointed to bypafter an unsuccessfulrealloc.