I am creating a dynamic array in c with malloc. eg:.
myCharArray = (char *) malloc(16);
Now, if I create such a function and pass it myCharArray:
reset(char * myCharArrayp) { free(myCharArrayp); }
will work, or am I somehow freeing only a copy of the pointer (myCharArrayp), and not the actual myCharArray?
It will be perfect and free up memory as you expect.
I would like to write a function like
void reset(char** myPointer) { if (myPointer) { free(*myPointer); *myPointer = NULL; } }
Thus, after releasing the pointer, it is set to NULL. Reusing previously freed pointers is a common source of errors.
, - , . , . . , , (, int), .
int
void myFunction() { char *myPointer; // <- the function stack frame is set up with space for... int myOtherVariable; // <- ... these two variables myPointer = malloc(123); // <- some memory is allocated on the heap and your pointer points to it free(myPointer); // <- the memory on the heap is deallocated } // <- the two local variables myPointer and myOtherVariable are freed as the function returns.
Yes, that will work.
Although a copy of your pointer variable will be sent, it will still refer to the correct memory location, which will actually be released with a free call.