FREE
D'Arcy J.M. Cain
darcy at druid.uucp
Wed Feb 28 02:51:33 AEST 1990
In article <2714 at stl.stc.co.uk> dsr at stl.stc.co.uk (David Riches) writes:
>We're writing a tool which requires memory management.
>We have a routine which allocates memory in the following
>fashion :-
> #define NE_ARR_MALLOC(y,n) ((y *) malloc ((unsigned) ((n) * (sizeof(y)))))
>
>Which will allocate space for n of y.
calloc does what you want and even initialize the space to zeroes for you.
To allocate n of y use:
x = (y *)calloc(n, sizeof(y);
where x is a pointer to type y. If using an ANSI compiler you can even leave
off the cast since calloc (and malloc) returns a pointer to void.
>
>The question then arises as how best to free this space?
>In most cases only the pointer to the space is known but will the
>following free up all the space :-
> #define NE_ARR_FREE(x) { free((char *) sizeof(x)); x = 0; }
>
>What happens to other references which might be pointing half way
>down the list for instance?
>
I'm afraid I can't parse the above statement. It seems to be saying that
the argument to free is the size of the array casted to a pointer. In any
case to free up space simply pass free the pointer to the malloc'ed space.
struct y *x;
unsigned nelems = NUMBER_OF ELEMENTS_REQUIRED_FOR_YOUR_APPLICATION;
...
x = malloc(nelems * sizeof(y));
/***** OR *****/
x = calloc(nelems, sizeof(y));
...
free(x);
--
D'Arcy J.M. Cain (darcy at druid) | Thank goodness we don't get all
D'Arcy Cain Consulting | the government we pay for.
West Hill, Ontario, Canada |
(416) 281-6094 |
More information about the Comp.lang.c
mailing list