I need to fill sparse matrix with random elemnts. I am trying to get random elements and write them as value, column and row elements of their arrays but I keep running into segmentation faults.
This only happens if I set N=1000 then SIZE=10000 (because if I set SIZE=1000 or less, it works).
Does that mean I can't allocate all this memory or access it after I allocated it?
What should I do if I really need to get all this memory (SIZE=10'000) allocated? can someone please help me?
#include <stdio.h>
#include <stdlib.h>
typedef struct _matrix {
int size; //number of not-null elements
int ord; //order of matrix
int* val;
int* col;
int* row;
} matrix;
matrix init (int ord, int size)
{
matrix m;
m.ord = ord;
m.size = size;
m.val = malloc(sizeof(int) * size);
m.val = malloc(sizeof(int) * size);
m.val = malloc(sizeof(int) * size);
return m;
}
matrix fill_matrix (int ord)
{
int i, j, gap, size = ord * ord / 100;
matrix new_matrix = init(ord, size);
j = 1;
for (i = 0; i < size; i++) {
new_matrix.val[i] = rand() % 9 + 1;
new_matrix.col[i] = rand() % ord + 1; //<------SEGFAULT
new_matrix.row[i] = rand() % ord + 1;
j++;
}
return new_matrix;
}
int main()
{
matrix A;
int n = 1000;
A = fill_matrix(n);
return 0;
}