I'm writing code to free a generic double pointer in C (void **ptr).
I believe there is not such thing as a generic double pointer. A pointer is just that: a pointer.
How do I check to see if the pointer was allocated via malloc/calloc?
You do not. A pointer is not allocated. Memory is allocated and the address of the area is assigned to a pointer.
How do I free the internal pointers? (I learned to do this by using a
for loop and being given the number of members in the pointer, but I
am not given that here.). The function declaration is
void freeArray(void **ptr);
"Internal pointer" is not a great description for this use, I believe.
Anyway, compare your function prototype with the usual main() prototype
int main(int argc, char** argv)
and you will see something is missing here.
Maybe it is more clear if you write
void** ptr = NULL;
You are declaring ptr
. As a pointer. But ptr
is allocated by now. It is static. May be 4 may be 8 bytes. And it points to a pointer to void
. Just this.
ptr
is void**
, *ptr
is void*
, **ptr
is void
. When using ptr
as a block of pointers you must do the same as the system does with main()
: build the block and keep your own argc
, the count of values. It is your problem to do that, or better, it is you problem NOT to do that.
Try this:
void freeArray(int ptrc, void** ptr);
And keep this pair always together and updated, so the part of "being given the number of members in the pointer" is a no brainer.
malloc
. You must design your program so it knows which things are allocated and which are not. The C standard does not provide any facility for this. (b) You do not free pointers. You allocate and free memory. If theptr
ofvoid **ptr
is pointing to pointers that point to allocated memory, you free that memory by passing each of those pointers tofree
. Your program must be designed to know how many such pointers there are.