Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Could you help me for memory leakage (http://www.go4expert.com/forums/help-memory-leakage-t19013/)

linshangxin 12Aug2009 22:00

Could you help me for memory leakage
 
Here is my program

Code: C++

class MEM{
public:
  float** GEN(void)
{
  float** X=(float**)malloc(sizeof(float)*3);
for (int Row=0; Row<3; Row++)
{
  X[Row]=(float*)malloc(sizeof(float)*3);
for (int Col=0; Col<3; Col++)
{
  X[Row][Col]=(float) rand();
}
}
return X;
free(X);
}

};

int main()
MEM test;
 for (int NT=0; NT<100; NT++)
{
  test.GEN();
}
return 0;


I found that the memory always can not be free. If the NT or 3 is very large, it will break the system. Could you help me how to free the memory in subprogram?

Thank you very much! Email: lshangxin2@student.cityu.edu.hk

xpi0t0s 12Aug2009 22:13

Re: Could you help me for memory leakage
 
Please use code blocks when posting code.

Your program doesn't free the memory it allocates. The free() call is after the return statement so will never be executed. Obviously it can't be in GEN() otherwise you can't return it to the calling function. So it needs to be in the calling function, which in this case is main().

Also it doesn't free all the memory it allocates. You free X itself, but you don't free X[n]. To avoid leaks, ALL malloc statements must be exactly matched with equivalent free statements. You have two mallocs and one free - a clear indication that there is a leak.

Code:

for (int NT=0; NT<100; NT++)
{
  float **foo=test.GEN();
  for (int i=0; i<3; i++)
    free(foo[i]);
  free foo;
}

Finally X should consistute pointers to float, not float. So:
Code:

float** X=(float**)malloc(sizeof(float*)*3);
and then X[n] is correctly of type float*.

linshangxin 12Aug2009 22:27

Re: Could you help me for memory leakage
 
Thank you very much. But I have test
Code:

float** X=(float**)malloc(sizeof(float)*3);
It can work well, Could you tell me why?

The other question:
When the foo have received the address, does it not matter the allocate memory in subprogram?

xpi0t0s 12Aug2009 23:45

Re: Could you help me for memory leakage
 
Probably because sizeof(float)=sizeof(float*), and at a guess probably both are 4 bytes. But as soon as this changes, your program will stop working.

No, it doesn't matter, because the memory is allocated on the heap which is available to the entire program, not on the stack which is only available locally within a function.

linshangxin 13Aug2009 10:10

Re: Could you help me for memory leakage
 
got it. Thank you very much!


All times are GMT +5.5. The time now is 21:02.