Path: utzoo!attcan!uunet!cs.utexas.edu!jarvis.csri.toronto.edu!torsqnt!hybrid!robohack!druid!darcy From: darcy@druid.uucp (D'Arcy J.M. Cain) Newsgroups: comp.lang.c Subject: Re: FREE Message-ID: <1990Feb27.155133.20341@druid.uucp> Date: 27 Feb 90 15:51:33 GMT References: <2714@stl.stc.co.uk> Reply-To: darcy@druid.UUCP (D'Arcy J.M. Cain) Organization: D'Arcy Cain Consulting, West Hill, Ontario Lines: 42 In article <2714@stl.stc.co.uk> dsr@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@druid) | Thank goodness we don't get all D'Arcy Cain Consulting | the government we pay for. West Hill, Ontario, Canada | (416) 281-6094 |