Search code examples
cpointersfree

freeing a triple pointer


After running this (it compiles fine), I get "double free or corruption", but only specifically if I set n to be odd. There's no problem for n even, and I'm really confused...

#include<stdio.h>
#include<stdlib.h>

typedef unsigned int uint;

int main(void)
{   
    int i, j;
    uint n = 3;

    uint*** a = (uint***) malloc( n* sizeof(uint**) );
    for(i=0; i<n; i++)
    {
        *(a + i) = (uint**) malloc( (n)* sizeof(uint*) );
        for(j=0; j<n; j++);
        {
            (*((*(a + i))+j)) = (uint*) malloc(1 * sizeof(uint));
        }
    }

    for(i=0; i<n; i++)
    {
        for(j=0; j<n; j++);
        {
            free (*((*(a + i))+j));
        }
        free (*(a + i));
    }
    free(a);
}

Solution

  • Here's your problem:

        for(j=0; j<n; j++);
    //                    ^
        {
            (*((*(a + i))+j)) = (uint*) malloc(1 * sizeof(uint));
    

    This extra ; at the end of the for line means you have a loop with an empty body:

        for(j=0; j<n; j++)
            ;
    

    ... followed by a single assignment:

            (*((*(a + i))+j)) = (uint*) malloc(1 * sizeof(uint));
    

    At this point j == n (because of the preceding loop), so you're writing out of bounds.

    The same bug exists further down in your free code (copy/paste?).