Memory leak when assigning pointers

4

I've been doing some tests with this code:

 int main()
 {
     int i;
     float *a, *b;


     a=(float*)malloc(sizeof(float)*10);

     b=(float*)malloc(sizeof(float)*20);

     b = a;  //FUGA DE MEMORIA??? 

     free(a); free(b); 
  }

My question is, as it appears in the comment, will there be a memory leak when assigning the value from "a" to "b", that is, I will not be able to release those 20 "floats" that I reserved for "b"? "?

And that line with two calls to free (), is one of them superfluous (or even dangerous)?

    
asked by Guillermo. D. S. 30.05.2018 в 12:51
source

1 answer

6
  

Will there be a memory leak when assigning the value from "a" to "b", that is, I will not be able to release those 20 "floats" that I reserved for "b"?

Correct. At the moment you lose the reference, the pointer, or whatever you want to call the memory block, you can not access the ... ergo you can not release it either.

  

And that line with two calls to free (), is one of them superfluous (or even dangerous)?

From even dangerous nothing. It is an error , and you incur indefinite behavior; since both variables point to the same site, what are you doing in releasing that block of memory 2 times ; You have guaranteed problems.

    
answered by 30.05.2018 / 12:56
source