0
int* a = (int*)malloc(5);
int* b = a;
free(b);

Is there memory leakage? If so, why does this occur?

  • 2
    No there isn't. (And you should not cast the return value of `malloc()`, BTW.) – Ken Y-N Jan 22 '18 at 01:30
  • As long as there's only one malloc and, at most, only one free operating on the same pointer VALUE as returned by the malloc, you're fine. If you malloc something, you can fre the pointer immediately after, assign it to another pointer var and free that, (as you have done above), pass it as an argument to another function that frees it, or return it to another function that frees it. You can even signal it to another thread, (not process), and free it there. One malloc, one free. – Martin James Jan 22 '18 at 02:18
  • don't cast the result of `malloc(3)`. Just do a proper `#include ` and you don't need to cast it to the final pointer type. That is better than casting it, as you get errors in case you do a typo in the types involved. – Luis Colorado Jan 22 '18 at 09:19
  • Not casting the result of `malloc` is in C tag [FAQ](https://stackoverflow.com/q/605845/3545273) – Serge Ballesta Jan 22 '18 at 09:31

3 Answers3

1

This doesn't leak memory, you free what you allocate, but both a and b are invalid after the free so using either of them is undefined behaviour.

tadman
  • 208,517
  • 23
  • 234
  • 262
0

No, this is perfectly safe. (Though you shouldn't cast malloc(). Casts are evil and should be avoided whenever possible. malloc() returns void *, which you never need to cast to a different pointer type)

One Guy Hacking
  • 1,176
  • 11
  • 16
  • [This answer](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) provides more deails. – tadman Jan 22 '18 at 01:34
0

In your case, there is no memory leakage but these pointers are called Dangling pointers.

Because you are delete object from memory but pointers still pointing same memory location.

 {
  int* a = (int*)malloc(5);
  int* b = a;
  free(b);  // a and b dangling now 
  a = b = NULL; //reset pointers // a and b are no longer dangling
}
Malik Ji
  • 339
  • 3
  • 13