RendoJack
RendoJack

Reputation: 366

Memory allocation. 2D array (Void function)

I followed few examples on this forum, but it seems like my program still keeps crashing at some point.

All i want to do is just use a void function for memory allocation.

void alloc(int ***matrix, int n)
{
    int i = 0;
    for( ; i < n; i++)
    {
        (*matrix)[i] = (int*)malloc(n * sizeof(int));
    }

    i = 0;
    for( ; i < n; i++)
    {
        int j = 0;
        for( ; j < n; j++)
        {
            (*matrix)[i][j] = i * j;
        }
    }
}

//-------------------------------------------------------------------
int main()
{
    int n;
    int **matrix_pp;

    printf("Enter n: ");
    scanf("%d", &n);

    alloc(&matrix_pp, n);

    free(matrix_pp);
    return 0;
}

Upvotes: 0

Views: 220

Answers (1)

R_Kapp
R_Kapp

Reputation: 2858

You try to use (*matrix)[i] before it's been allocated. Add:

 (*matrix) = malloc(n * sizeof(**matrix));

before your for loop.

Note two things here:

1) Don't cast the result of malloc,

2) use sizeof(*pointer) instead of explicitly writing out the type; this way, if you decide to change the type later, it will still work.

Further, you will need to free all of the allocations you have in a loop as a loop as well; otherwise, you have a memory leak.

Upvotes: 3

Related Questions