Yktula
Yktula

Reputation: 14809

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?

Upvotes: 2

Views: 947

Answers (4)

Nordic Mainframe
Nordic Mainframe

Reputation: 28747

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

Upvotes: 4

Cheery
Cheery

Reputation: 25433

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

Upvotes: 3

Mak Kolybabi
Mak Kolybabi

Reputation: 364

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.

Upvotes: 2

Matthew Flaschen
Matthew Flaschen

Reputation: 284836

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.

Upvotes: 5

Related Questions