Here is my program Code: 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
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*.
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?
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.