Following is the implementation of a stack struct in C. I need to write a function (not a method) to dispose off an existing stack and ofcourse free any memory allocated for it on the heap. the dispose (stack *s) function takes in a pointer to a stack that is to be disposed off.
typedef struct {
int allocatedLength;
int logicalLength;
int elementSize;
void *elems;
} stack;
If I implement the dispose() function as follows, will it lead to some memory never being freed?
void dispose (stack *s) {
free (s->elems);
}
In the above implementation, I am only freeing the memory allocated to elems, which is not even on the heap. We need to remember that elems is a pointer to something. Shouldn’t we be freeing that something, instead of freeing the memory allocated to the pointer?
You misunderstand:
free(p)does not free the memory forp, but the memory for*p— that is, the memory pointed to byp. Thus, you are correctly freeing the allocated memory to which you stored a pointer ins->elems, and all is well.Feel free to blame everyone who talks about “freeing a pointer” for this misnomer, when really they should be saying “freeing the memory to which I have a pointer”.