free the space allocated in c with malloc
c, free, malloc, struct, typedef
Solution
That is correct.
To help avoid shooting yourself in the foot, you might consider the following practices:
- Always free all malloc/calloc'ed memory with free()
- Afterwards, set the pointer to NULL
- Use a dedicated cleanup/destroy function to ensure consistent memory cleanup
The following function would be a good way to make sure you always cleanup a structure properly, avoid memory leaks, and avoid accidentally freeing already-freed memory and causing a segmentation fault:
int destroyNode(Node* myNode) {
if(!myNode) {
printf("Invalid pointer! Exiting");
return (-1);
}
// Clear out memory
if(np) {
free(np);
np = NULL;
}
if(R) {
free(R);
R = NULL;
}
if(C) {
free(C);
C = NULL;
}
if(ptrTempLst) {
free(ptrTempLst);
ptrTempLst = NULL;
}
if(leftTree) {
free(leftTree);
leftTree = NULL;
}
if(rightTree) {
free(rightTree);
rightTree = NULL;
}
free(myNode);
}
eg:
int main(void) {
Node *tempNode = calloc((size_t)1,sizeof(Node));
// Alloc the member nodes, etc, do some code
// Ready to clean up and exit program
destroyNode(tempNode);
tempNode = NULL;
return 0;
}
Good luck!
Problem
I have a question about this code: ``` typedef struct pop { unsigned long int *np; // matrix unsigned long int f; long double fp; unsigned long int *R; // matrix unsigned long int *C; // matrix unsigned long int Dp; unsigned long int Ds; unsigned long int count; struct popolazione *ptrTempLst; // pointer struct popolazione *leftTree; // left tree pointer struct popolazione *rightTree; // right tree pointer } Node; ``` When I free space allocated for this struct, prior have I to free pointer to matrix inside struct? For example, ``` Node *ptr=(Node *) malloc(sizeOf(Node)); ptr->np=(unsigned long int *)malloc(10*sizeOf(unsigned long int)); /*code code code*/ // is necessary: free(ptr->np); free(ptr); ``` Thanks in advance