Free up space allocated in c with malloc

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 the space allocated for this structure, should I free the pointer to the matrix inside the struct before?

For instance,

  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

+6
source share
2 answers

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)); // Alloc the member nodes, etc, do some code // Ready to clean up and exit program destroyNode(tempNode); tempNode = NULL; return 0; } 

Good luck

+6
source

Yes.

Each call to malloc must have a corresponding call to free .

+9
source

Source: https://habr.com/ru/post/916592/


All Articles