For example, I want such a function:
char *dst = (char*)malloc(512);
char *src = (char*)malloc(1024);
...
dst = (char*)realloc(dst, 1024);
memcpy(dst, src, 1024);
As you see, I just want the function realloc() to extend the size of buffer, but the realloc() in C library may copy data from old address. So is there a function in any library like what I want?
Why not just:
free(dst);
dst = malloc(1024);
Also note that realloc
may move the block as well as resizing it, so holding an old pointer returned by a previous call to malloc
, calloc
or realloc
may no longer refer to the same chunk.
realloc
attempts do extend the buffer without copying, but can only do that if the extra space is free.
In your case, you just allocated space for src
and that memory block just might have used the space realloc
would have needed. In that case it can only allocate a larger block somewhere else and copy the data to that block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With