Search code examples
cmemoryrealloc

Why is there no function in standard C library like realloc() without data copying?


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?


Solution

  • 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.