简体   繁体   English

重新分配数组(C99)

[英]Reallocating an array (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? 实现数据结构的最佳方法是像动态增长的数组一样只能以链表的形式增长吗?

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 . p的前6个字符保证为'H','e','l','l','o','\\ 0',无论新p是否与旧p相同。 The remaining 6 "new" chars are all that's undefined. 其余6个“新”字符都是未定义的。

"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. 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(). 不需要hacks,只需realloc()。

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. 例如,如果你有一个包含10个元素的数组,并且你将它重新分配给20个元素足够大,那么最后10个元素将是未定义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM