简体   繁体   中英

How to clear memory in c

I have a struct as follows:

struct Node{
int *arr;
int *sol;
struct Node *Next;
};

i am creating Node in this way:

Node* MyNode = (Node *)malloc(sizeof (struct Node));
MyNode->arr = malloc(sizeof(int)*N);
MyNode->sol=  malloc(sizeof(int)*N);

I then add MyNode to a linked list. How can i free memory for an element in the list.
is this correct:

pop(){
   free(first->arr);
   free(first->sol);
   first=first->Next; 
}

For any struct to be a node in a linked-list , you need a self-referential structure variable which should be declared as struct Node *next;

struct Node{
    int *arr;
    int *sol;
    struct Node *next;
}

To allocate memory for a node of a linked-list, you need the following:

/* allocate memory for a node */
struct Node * MyNode = (struct Node *)malloc((int)sizeof(struct Node));
if (MyNode == NULL) {
    printf("ERROR: unable to allocate memory \n");
    return 1;
}

/* allocate memory for the content of a node */
MyNode->arr = (int *) malloc((int)sizeof(int) * N);
if (MyNode->arr == NULL) {
    printf("ERROR: unable to allocate memory \n");
    return 1;
}

MyNode->sol = (int *) malloc((int)sizeof(int) * N);
if (MyNode->sol == NULL) {
    printf("ERROR: unable to allocate memory \n");
    return 1;
}

/* add the new node to a list by updating the next variable */
MyNode->next = ... 

If you are not sure about the operations that you need to perform to delete node in a linked-list, you can use a temp variable to do the same in an easier way.

pop()
{
    struct Node * temp = first;
    first = first->next;
    free(temp->arr);
    free(temp->sol);
    free(temp);
}

Thumb rule for free - for every malloc() there should be a free()

OTOH, to go through various scenarios in deleting a node in an linked-list, please refer this link.

almost, you need to free the node itself:

pop(){
   Node* old_first = first;
   free(first->arr);
   free(first->sol);
   first=first->Next;
   free(old_first); 
}
pop(){
   free(first->arr);
   free(first->sol);
   Node* temp = first; //<========
   first=first->Next;
   free (temp);  //<=======
}

It's close but not correct - you should have as many free s as you have malloc s. You're forgetting to free the Node itself.

To fix it, add a temporary:

Node *next = first->next;
free(first->arr);
free(first->sol);
free(first); 
first = next;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM