Aj_76
Aj_76

Reputation: 39

C segfault with calloc

These two lines are giving me a segfault and I can't figure it out:

int** input;
*input = (int*)calloc(5, sizeof(int));

That's it. The way I understand this is, request memory equal to 5 ints and return the memory address. store the memory address in the value pointed to by input. What am I missing?

Upvotes: 1

Views: 2831

Answers (2)

Sarah Roberts
Sarah Roberts

Reputation: 860

The problem is that you're trying to assign to an address that hasn't been allocated yet. If you assign the value directly to input then it should work.

input = (int *) calloc(5, sizeof(int));

EDIT: I forgot to update the cast, and I thought some more explanation was in order.

The allocation should have been this:

input = calloc(5, sizeof(int *));

What this does is allocate an array of 5 integer pointers. Once you have that, you can allocate arrays of integers to store inside those integer pointers. (Note: I'm assuming C99 support here.

for (int i = 0; i < 5; i++) {
    input[i] = calloc(5, sizeof(int));
}

What this does is allocate a 5-by-5 matrix of integers, and it's essentially the same as declaring input as follows:

int input[5][5];

The difference is that in this declaration, the compiler manages the allocation for you, which may or may not be what you want. For example, if this code is in a function and you want to return a pointer to the matrix that you've allocated then you'll want to allocate the memory yourself. If you're only using the data structure within the current function then letting the compiler manage the memory will work fine.

Upvotes: 0

Musa
Musa

Reputation: 97707

You never initialize input so referencing whatever happens to be there, maybe this is what you want

int** input;
input = malloc(sizeof(int*));
*input = calloc(5, sizeof(int));

Upvotes: 7

Related Questions