prev up next   top/contents search

comp.lang.c FAQ list · Question 7.29

Q: Having dynamically allocated an array (as in question 6.14), can I change its size?


A: Yes. This is exactly what realloc is for. Given a region of malloced memory (such as dynarray from question 6.14), its size can be changed using code like:

	dynarray = realloc(dynarray, 20 * sizeof(int));
Note that realloc may not always be able to enlarge [footnote] memory regions in-place. When it is able to, it simply gives you back the same pointer you handed it, but if it must go to some other part of memory to find enough contiguous space, it will return a different pointer (and the previous pointer value will become unusable).

If realloc cannot find enough space at all, it returns a null pointer, and leaves the previous region allocated. [footnote] Therefore, you usually don't want to immediately assign the new pointer to the old variable. Instead, use a temporary pointer:

	#include <stdio.h>
	#include <stdlib.h>

	int *newarray = (int *)realloc((void *)dynarray, 20 * sizeof(int));
	if(newarray != NULL)
		dynarray = newarray;
	else {
		fprintf(stderr, "Can't reallocate memory\n");
		/* dynarray remains allocated */
	}

When reallocating memory, be careful if there are any other pointers lying around which point into (``alias'') that memory: if realloc must locate the new region somewhere else, those other pointers must also be adjusted. Here is a (contrived, and careless of malloc's return values) example:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *p, *p2, *newp;
int tmpoffset;

p = malloc(10);
strcpy(p, "Hello,");		/* p is a string */
p2 = strchr(p, ',');		/* p2 points into that string */

tmpoffset = p2 - p;
newp = realloc(p, 20);
if(newp != NULL) {
	p = newp;		/* p may have moved */
	p2 = p + tmpoffset;	/* relocate p2 as well */
	strcpy(p2, ", world!");
}

printf("%s\n", p);
(It is safest to recompute pointers based on offsets, as in the code fragment above. The alternative--relocating pointers based on the difference, newp - p, between the base pointer's value before and after the realloc--is not guaranteed to work, because pointer subtraction is only defined when performed on pointers into the same object. See also question 7.21.)

See also questions 7.7 and 7.30.

References: K&R2 Sec. B5 p. 252
ISO Sec. 7.10.3.4
H&S Sec. 16.3 pp. 387-8


prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North