user3764250
user3764250

Reputation: 11

free the pointer memory after the function call

I am having simple doubt regarding the memory leak and memory free in C. Here is my simple example

typedef struct{
     uint16 a;
     uint8 b[3];
     uint8 c;
}log_msg;

typedef struct node{
     log_msg list;
     struct node *next;
}logs_t;

This is the structure I have. If I store the Data in the structure. Then if I want to access the structure with a pointer to check the list of msg_log. It is necessary to de allocate the pointer/ free it. Example,

ret = Check_the_list(data);

uint8 Check_the_list(uint16 data)
{
     logs_t *ptr = NULL;
     uint8 brk = 0;
     ptr = top;
     while(ptr != NULL && brk == 0)
     {
        if(ptr->list.a == data)
        {
            brk = 1;
            return 0;
        }
        else
        {
            ptr = ptr->next;
        }
     }
     return 1;
  }

It is necessary to de allocate/free ptr here.This will cause memory leaks, if this function calls multiple number of times and I am not freeing the ptr?. As I know, this will de allocate automatically after function call, because I am not using dynamic memory. But even though I want to confirm with experts. So I request experts to suggest me.

Upvotes: 1

Views: 93

Answers (2)

Maxime Chéramy
Maxime Chéramy

Reputation: 18851

Your variable ptr is a number allocated on the stack that contains an address. The stack is "freed" when your function returns. There is nothing else to free.

You should do the same number of free that the number of malloc. If you do no malloc, you should not free anything. If you try to free ptr, it will free the element pointed by ptr which is not something you want.

Upvotes: 0

P.P
P.P

Reputation: 121427

Yes, you don't have to free() anything as you haven't allocated any memory for ptr in Check_the_list().

The easy way to remember is whenever you do a malloc()/calloc()/realloc(), then you do a free().

Aside: Your loop condition using brk is not necessary as you return immediately after finding data. So brk == 0 needless and you could eliminate brk completely:

 while(ptr != NULL)
     {
        if(ptr->list.a == data)
        {
         return 0;
        }
        else
        {
         ptr = ptr->next;
        }
     }

Upvotes: 1

Related Questions