Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 766
Yktula Avatar asked Jan 23 '26 00:01

Yktula


1 Answers

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.

like image 104
Matthew Flaschen Avatar answered Jan 24 '26 17:01

Matthew Flaschen