I am writing in simple C, and I have a problem with how to free a pointer to a structure. I have a structure declared as follows.
typedef struct _RealMatrix { uint nRows; uint nCols; real **matrix; } RealMatrix;
Now, every time I need it, I use the following code to highlight it
RealMatrix *realMatrixAlloc(uint n, uint m) { loop_var(i); RealMatrix *matrix; matrix = malloc(sizeof(RealMatrix)); errcheck(matrix, "Unable to create real matrix structure."); matrix->nRows = n; matrix->nCols = m; matrix->matrix = malloc(n*sizeof(real *)); matrix->matrix[0] = malloc(n*m*sizeof(real)); errcheck(matrix->matrix && matrix->matrix[0], "Unable to get requested memory for real matrix of dimensions: (%u, %u).", n, m); f_i(i < n) matrix->matrix[i] = matrix->matrix[0] + i*m; return matrix; }
where errcheck () is the distribution check macro. Everything works fine until I try to free it by calling
freeRealMatrix(&myRealMatrix);
which will
free((*ma)->matrix[0]), free((*ma)->matrix) free(*ma). *ma = NULL;
with appropriate checks to avoid following the NULL pointer. Here "ma" is the TO POINTER pointer to the structure: the function declaration reads
void freeRealMatrix(RealMatrix **ma);
However, when this function returns, I find out that "myRealMatrix" still refers to an existing structure that was not released as I expected for free (* ma). On the other hand, the matrix (* ma) → has been successfully deleted.
Any ideas on what I'm doing wrong? It drives me crazy ... Thanks in advance!
UPDATE:
I copied the code and executed in a new program ... It works exactly as expected. I noticed that the address contained in "myRealMatrix" does not match the address indicated by * ma. Well ... Grade: seems truncated! Instead of 0x106a50 it is only 0x106a and no more. The last two hexadecimal digits are missing every time!