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

北战南征 提交于 2019-12-23 19:12:16

问题


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?


回答1:


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.




回答2:


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.




回答3:


So is there a function in any library like what I want?

No there is not. How is the system supposed to extend the piece of memory if there isn't room ?

e.g. imagine you do this:

char *a = malloc(2);
char *b = malloc(2);

The memory allocated might now look like:

1   2   3   4   5   6   7
-------------------------
|   |   |   |   |   |   |
-------------------------
\      /\       /\      /        
 \    /  \     /  \    /
   v        v        v
 memory   unused/   memory
 for "a"  internal   for "b"
         memory piece

Now you do realloc(a,10); . The system can't simply extend the memory piece for "a". It'll hit the memory used by "b", so instead it has to find another place in memory that has 10 contiguous free bytes , copy over the the 2 bytes from the old memory piece and return you a pointer to these new 10 bytes.



来源:https://stackoverflow.com/questions/6696006/why-is-there-no-function-in-standard-c-library-like-realloc-without-data-copyi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!