Chaos
Chaos

Reputation: 209

Allocate a matrix in C using malloc

I wrote a C code that usea a matrix of double:

double y[LENGTH][4];

whith LENGTH=200000 I have no problem.

I have to increase the numbers of rows to LENGTH=1000000 but when I enter this value and execute the program it returns me segmentation fault.

I tried to allocate more memory using malloc:

double **y = (double **)malloc(LENGTH * sizeof(double*));
for(int i = 0; i < LENGTH; i++){
  y[i] = (double *)malloc(4 * sizeof(double));
}

I run the the code above and after some second of calculations it still gives me "segmentation fault". Could anyone help me?

Upvotes: 2

Views: 3029

Answers (3)

WhozCraig
WhozCraig

Reputation: 66254

If you want a dynamic allocated 2D array of the specified row-width, just do this:

double (*y)[4] = malloc(LENGTH * sizeof(*y));

There is no need to malloc each row in the matrix. A single malloc and free will suffice. Only if you need dynamic row width (each row can vary in width independent of others) or the column count is arbitrary should a nested malloc loop be considered. Neither appears to be your case here.

Notes:

Upvotes: 3

gsamaras
gsamaras

Reputation: 73444

I run this code

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

// We return the pointer
int **get(int N, int M) /* Allocate the array */
{
    /* Check if allocation succeeded. (check for NULL pointer) */
    int i, **table;
    table = malloc(N*sizeof(int *));
    for(i = 0 ; i < N ; i++)
        table[i] = malloc( M*sizeof(int) );
    return table;
}

void free2Darray(int** p, int N) {
    int i;
    for(i = 0 ; i < N ; i++)
        free(p[i]);
    free(p);
}

int main(void)
{
    const int LENGTH = 1000000;
    int **p;
    p = get(LENGTH, 4);
    printf("ok\n");
    free2Darray(p ,LENGTH);
    printf("exiting ok\n");
    return 0;
}

and it was executed normally.

I got the code from my pseudo-site.

You should not cast what malloc returns. Why?

Also notice, that since you need a dynamic allocation only for the number of rows, since you know the number of columns. So, you can modify the code yourself (so that you have some fun too. :) )

I hope you didn't forget to **free** your memory.

Upvotes: 0

Josh
Josh

Reputation: 8026

The reason your statically allocated array is segfaulting with a million elements is (presumably) because it's being allocated on the stack. To have your program have a larger stack, pass appropriate switches to your compiler.

ProTip: You will experience less memory fragmentation and better performance if you flip your loop around, allocating

    (double *)malloc(LENGTH * sizeof(double));

four times. This will require changing the order of your indices.

I ran the the code with this definition and after some second of calculations it still gives me "segmentatin fault"

If you're getting a segmentation fault after allocating the memory, you're writing outside of your memory bounds.

Upvotes: 2

Related Questions