0
row = n + 1;
col = n + 1;
//used n+1 and i=-1 to avoid segmentation faults

board = malloc(row*sizeof(char *));
for(i=-1;i<row;i++)
{       
    board[i] = malloc(col*sizeof(char));
    if(board[i] == NULL)
    {
        printf("Out of memory");
            exit(EXIT_FAILURE);
    }
}

for(i=-1; i < n+1; ++i)
{
    free(board [i]);
}
free(board);

When I try to free this array in run time, my compiler goes berserk, please explain, thank you.

2 Answers2

5

arrays cannot have negative index in C.

at the line: for(i = -1; i < row; i++)

I am very sure, there is an off by one error here, where free is freeing one extra block that was not malloc()ed at the end, and you must be getting a segfault error.

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
  • 1
    I am unsure if the negative index is a compile error or not (don't think so since `*(ptr - 1)` is valid), but when @user assigns to board[-1] there is definitely going to be undefined behaviour. @user, listen to this guy, and please, never try to index into an array with a negative number. :) – Nava2 Nov 08 '13 at 04:08
0

malloc returns void pointer, you must cast it. Also minimum index is zero in C.

    board = (char**)malloc(row*sizeof(char *));
    for(i=0;i<row;i++)
    {       
        board[i] = (char*)malloc(col*sizeof(char));
        if(board[i] == NULL)
        {
        printf("Out of memory");
            exit(EXIT_FAILURE);
        }
    }
Polymorphism
  • 249
  • 1
  • 9