重新分配数组 (C99)
标准指定如果新的空间被重新分配,那么重新分配的空间的内容是未定义的。尺寸如果更大。
如果保留先前分配的空间的内容很重要,那么重新分配数据的最佳方法是否如下:将其复制到堆栈,从堆中释放它,在堆上分配更多空间,然后复制回堆?还有其他安全的方法吗?
实现像只增长的动态增长数组这样的数据结构的最佳方法是链表的形式吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
“对象的新分配部分的内容未指定。”您的内容仍将位于返回的内存区域的开头。
说我愿意:
p
处的前 6 个字符保证为 'H'、'e'、'l'、'l'、'o'、'\0',无论是否是 newp
与旧的p
相同。剩下的 6 个“新”字符都是未定义的。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:
The first 6 characters at
p
are guaranteed to be 'H', 'e', 'l', 'l', 'o', '\0', regardless of whether newp
is the same as oldp
. The remaining 6 "new" chars are all that's undefined.“该标准规定,如果新大小较大,则重新分配空间的内容是未定义的。”
不,没有。它说:
“对象的内容应保持不变,直至新旧尺寸中较小的一个。”
“如果新大小更大,则对象新分配部分的内容未指定。”
仅新部分的内容未指定。重新分配后不会丢失任何内容。
"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.
您误读了该页面。它说:“对象的内容应保持不变,直至新旧尺寸中较小的一个。”
不需要 hack,只需 realloc()。
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().
只有内存的新部分是未定义的。例如,如果您有一个包含 10 个元素的数组,并且您将其重新分配到足以容纳 20 个元素,则最后 10 个元素将是未定义的。
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.