Reallocating an array (C99)

心已入冬 提交于 2019-12-12 18:15:31

问题


The standard specifies that the contents of reallocated space is undefined if the new size if larger.

If preserving the contents of the previously-allocated space is important, is the best way to reallocate data as follows: copying it to the stack, freeing it from the heap, allocating on the heap with more space, and copying back to the heap? Is there another safe way to do this?

Would the best way to implement a data structure like a dynamically growing array that only grows be in the form a linked list?


回答1:


The contents of the "newly allocated portion of the object are unspecified." Your content will still be at the beginning of the returned memory region.

Say I do:

char *p = malloc(6);
if(p == NULL) { ... }
memcpy(p, "Hello", 6);
char *temp = realloc(p, 12);
if(temp == NULL) { ... }
p = temp;

The first 6 characters at p are guaranteed to be 'H', 'e', 'l', 'l', 'o', '\0', regardless of whether new p is the same as old p. The remaining 6 "new" chars are all that's undefined.




回答2:


"The standard specifies that the contents of reallocated space is undefined if the new size if larger."

No it doesn't. It says:

"The contents of the object shall remain unchanged up to the lesser of the new and old sizes." "If the new size is larger, the contents of the newly allocated portion of the object are unspecified."

Only the contents of the new part are unspecified. Nothing is lost after realloc.




回答3:


You are misreading the page. It says: "The contents of the object shall remain unchanged up to the lesser of the new and old sizes."

No hacks required, just realloc().




回答4:


Only the new portion of the memory is undefined. For instance, if you had an array of 10 elements, and you realloc'd it to be large enough for 20 elements, the last 10 elements would be undefined.



来源:https://stackoverflow.com/questions/3294396/reallocating-an-array-c99

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