user3142434
user3142434

Reputation: 305

free() causes SEG fault C

int ** ARR;
int LENGTH = 1;
int DEPTH = 1;

void loadt(int ** terr)
{
    terr = (int**)malloc(sizeof(int*) * (LENGTH + 1));
    int i, j;
    for(i = 1; i <= LENGTH; i++)
        terr[i] = (int*)malloc(sizeof(int) * (DEPTH + 1));
    for(i = 1; i <= LENGTH; i++)
        for(j = 1; j <= DEPTH; j++)
            scanf("%d", &terr[i][j]);
}
void freet(int ** terr)
{
    int i;
    for(i = 1; i <= LENGTH; i++){
        free(terr[i]);
    }
    free(terr);
}

int main(int argc, char* argv[])
{
    loadt(ARR);
    freet(ARR);  
    return 0;
}

Hello. I probably miss sth really basic here but after I run the program it crashes."Segmentation fault (core dumped)" Why?

Upvotes: 1

Views: 69

Answers (1)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

Because in arguments to functions are always passed by value, so your unecessarily global variable is not getting reassigned inside the function since you are passing it as a parameter and hence a copy of it is made, which is the one that is actually reassigned.

So you are calling free() on an uninitialized poitner.

Try like this

int **loadt(int LENGTH, int DEPTH)
{
    int **terr;
    int i, j;
    terr = malloc(sizeof(int*) * (LENGTH + 1));
    if (terr == NULL)
        return NULL;
    for (i = 1; i <= LENGTH; i++) {
        terr[i] = malloc(sizeof(int) * (DEPTH + 1));
        if (terr[i] == NULL) {
            for (j = i ; j >= 0 ; --j) {
                free(terr[j]);
            }
            free(terr);
            return NULL;
        }
    }
    for (i = 1; i <= LENGTH; i++) {
        for (j = 1; j <= DEPTH; j++) {
            scanf("%d", &terr[i][j]);
        }
    }
    return terr;
}

void freet(int **terr)
{
    int i;
    if (terr == NULL)
        return; // `free()' also accepts NULL pointers
    for (i = 1; i <= LENGTH; i++) {
        free(terr[i]);
    }
    free(terr);
}

int main(int argc, char* argv[])
{

    int **ARR;
    int LENGTH = 1;
    int DEPTH = 1;

    ARR = loadt(LENGTH, DEPTH);
    freet(ARR);  
    return 0;
}

Another problem, is that you start your loops at i = 1, which is fine because you are allocating enough space, but it's not the way you should do it. Instead for (i = 0 ; i < LENGTH ; ++i) would be how a programmer would do it. Note that you are wasting the first element of your array.

Upvotes: 4

Related Questions