Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

memory

realloc

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?

like image 457
legendlee Avatar asked Jul 14 '11 15:07

legendlee


2 Answers

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.

like image 93
Blagovest Buyukliev Avatar answered Sep 20 '22 03:09

Blagovest Buyukliev


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.

like image 23
Bo Persson Avatar answered Sep 18 '22 03:09

Bo Persson