realloc primer
Mark Brader
msb at sq.sq.com
Wed Feb 13 08:23:40 AEST 1991
In an otherwise excellent article, Steve Summit (scs at adam.mit.edu) writes:
> The transformation from fixed-size to dynamically-allocated is
> simple: just change the array to a pointer, and add another
> variable keeping track of how many slots have been allocated.
> (... you [may not] even need the extra variable. ...)
>
> With one exception, no appearances of the global array (which is
> now actually a pointer) in the rest of the code have to be
> changed, because pointers can be subscripted the same as arrays ...
> One thing to beware of when using realloc is that the array can
> (and usually will) move around in memory, invalidating any other
> pointers to elements within it. (This is the "one exception" I
> alluded to above.)
There is in fact a second important exception: sizeof. For instance,
given "int arr[N];", some people prefer to write
if (i < sizeof arr / sizeof arr[0])
arr[i++] = new_item;
else
error...;
rather than
if (i < N)
arr[i++] = new_item;
else
error...;
because in the second form you have to look back to the declaration to
verify that that N means what you think it does. And such expressions
may occur in other places, such as loop headers.
A still worse case is this one:
if (restoring)
fread (arr, sizeof arr, 1, fp);
...;
if (saving)
fwrite (arr, sizeof arr, 1, fp);
Here the *file format* was designed for a fixed-size array, and if it is
to be replaced by a dynamic one, the format will have to be changed so
that a count can be read from the file before the array itself.
And while you're fixing *those* problems, you can also correct the fread
and fwrite calls, which should probably look more like this:
count = fread ((char *) arr, size, 1, fp);
if (count < 1) {
fprintf (stderr, "%s: error reading %s..."...);
exit(1);
}
(In ANSI C the type "char *" becomes "void *", and the cast can be
removed anyway if a prototype is in scope. Whether it is desirable
is a matter of style. It's harmless to leave a char * cast in anyway.)
--
Mark Brader "It's simply a matter of style, and while there
SoftQuad Inc., Toronto are many wrong styles, there really isn't any
utzoo!sq!msb, msb at sq.com one right style." -- Ray Butterworth
This article is in the public domain.
More information about the Comp.lang.c
mailing list