2

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); 
3
  • 4
    This will indeed lead to a memory leak. p is no longer pointing to the allocated memory chunk (and neither is anything else), so you cannot free it. Commented Feb 10, 2020 at 20:27
  • 5
    You never free it so you leak it. It has nothing to do with malloc, though. Commented Feb 10, 2020 at 20:27
  • 2
    You also don't need to cast malloc. Commented Feb 10, 2020 at 20:30

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

you don't need to cast malloc, this is C.
I just copied their code. I'll do some other cleanup and remove it.
2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.