views:

102

answers:

4

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?

+5  A: 

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.

Matthew Flaschen
+2  A: 

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.

Mak Kolybabi
+2  A: 

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().

Cheery
+4  A: 

"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.

Luther Blissett