Reputation: 23
I've got the following faulty piece of code in C and I am wondering if there will be a memory leak or if there will be a pointer which is pointing to a free memory location.
int* p = (int*) malloc(sizeof(int));
p = NULL;
free(p);
Upvotes: 2
Views: 775
Reputation: 1722
Yes it will leak memory. You assign p to NULL before freeing the contents it's pointing to. One quick change will fix it:
int* p = malloc(sizeof(int));
free(p);
p = NULL;
The difference here is we give free the address allocated by malloc before setting p to NULL. In general setting a pointer to NULL will not free the contents, but will allow you to check if the pointer is valid or not which can have a lot of practical applications.
Upvotes: 4
Reputation: 2652
You will have a memory leak.
After you assign NULL
to p
, you no longer have a way to refer to the memory you allocated with malloc
.
Your call to free
will try to free NULL
, doing nothing.
The following will correctly free the memory:
int *p = malloc(sizeof(int));
free(p);
p = NULL;
Note that you don't need to set p
to NULL
after freeing, you only really need the first two lines.
Upvotes: 2