Note that there are some explanatory texts on larger screens.

plurals
  1. POc free pointer to structure
    text
    copied!<p>I'm writing in plain C and I have an issue about how to free a pointer to a structure. I have a structure declared in the following way</p> <pre><code>typedef struct _RealMatrix { uint nRows; uint nCols; real **matrix; } RealMatrix; </code></pre> <p>Now, every time I need it I use the following code to allocate it</p> <pre><code>RealMatrix *realMatrixAlloc(uint n, uint m) { loop_var(i); RealMatrix *matrix; matrix = malloc(sizeof(RealMatrix)); errcheck(matrix, "Unable to create real matrix structure."); matrix-&gt;nRows = n; matrix-&gt;nCols = m; matrix-&gt;matrix = malloc(n*sizeof(real *)); matrix-&gt;matrix[0] = malloc(n*m*sizeof(real)); errcheck(matrix-&gt;matrix &amp;&amp; matrix-&gt;matrix[0], "Unable to get requested memory for real matrix of dimensions: (%u, %u).", n, m); f_i(i &lt; n) matrix-&gt;matrix[i] = matrix-&gt;matrix[0] + i*m; return matrix; } </code></pre> <p>where errcheck() is a allocation checking macro. Everything works just fine until I try to deallocate it calling</p> <pre><code>freeRealMatrix(&amp;myRealMatrix); </code></pre> <p>which will</p> <pre><code>free((*ma)-&gt;matrix[0]), free((*ma)-&gt;matrix) free(*ma). *ma = NULL; </code></pre> <p>with suitable checks to avoid following any NULL pointer. Here "ma" is the pointer TO THE POINTER to the structure: the function declaration reads</p> <pre><code>void freeRealMatrix(RealMatrix **ma); </code></pre> <p>However when this function returns I find out that "myRealMatrix" is still addressing an existing structure, which was not deallocated as I expected by free(*ma). On the other hand the array (*ma)->matrix has been successfully deallocated.</p> <p>Any ideas about what am I doing wrong? This is driving me crazy... Thanks in advance!</p> <p>UPDATE:</p> <p>I copied the code and executed in a brand new program... It works precisely as expected. I noticed that the address contained in "myRealMatrix" isn't the same as the address pointed by *ma. Well... Sort of: it seems truncated! Instead of being 0x106a50 it is just 0x106a and no more. The last two hex digits are missing every time!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload