1
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?

user3142434
  • 305
  • 3
  • 15
  • [Please see this discussion on why not to cast the return value of `malloc()` and family in `C`.](http://stackoverflow.com/q/605845/2173917). – Sourav Ghosh Dec 21 '15 at 14:07
  • Why do you pass a global variable to the functions as arguments? While I advocate against using global variables, if you modified the code to use the global variable instead that would solve your problem. – Some programmer dude Dec 21 '15 at 14:09

1 Answers1

4

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.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97