0

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;
}

2 Answers 2

2

You assign to val three times, but never initialize the other two pointers.

m.val = malloc(sizeof(int) * size);
m.val = malloc(sizeof(int) * size);
m.val = malloc(sizeof(int) * size);

I'm guessing you meant this:

m.val = malloc(sizeof(int) * size);
m.col = malloc(sizeof(int) * size);
m.row = malloc(sizeof(int) * size);
Sign up to request clarification or add additional context in comments.

Comments

2
m.val = malloc(sizeof(int) * size);
m.val = malloc(sizeof(int) * size);
m.val = malloc(sizeof(int) * size);

You never malloc m.col and m.row :-) Cut & Paste programming is evil...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.