It is right.
To avoid shooting in the leg, you can consider the following actions:
- Always free malloc / calloc'ed memory with free ()
- Then set the pointer to NULL
- Use the special wipe / kill function to ensure that memory is constantly cleared.
The following function is a good way to make sure that you always clean the structure correctly, avoid memory leaks and avoid accidentally freeing already freed memory and cause a segmentation error:
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));
Good luck
source share