Arnaud Courtecuisse
Arnaud Courtecuisse

Reputation: 367

Segfault when initializing 2d array

I cannot find what's wrong in this simple array initialization. The program crashes with a segfault on field[x][y] = ' ';, x and y at 0 (I use Code::Blocks debugger)

/* init data structures */
char **field;
int field_width=5,field_height=5;
field = malloc(sizeof(char*)*field_width);
for(x=0;x<field_width;x++)
{
    field[x] = malloc(sizeof(char)*field_height);
    for(y=0;y<field_height;y++)
    {
        field[x][y] = ' ';
    }
}

Any idea of what I am doing wrong ?

Upvotes: 0

Views: 177

Answers (4)

Joshua Green
Joshua Green

Reputation: 1575

Before you initialized field_width, it probably contained random data. Using field_width in the malloc statement then triggered undefined behavior. The compiler could do whatever it wanted, from skipping the malloc to using whatever garbage happened to be stored in field_width, or even worse/stranger things!. Regardless, you were unlikely to get the malloc call you wanted, and either if it didn't run or returned NULL (e.g. if field_width contained a value that was too large to be malloced), the resulting value of field was unlikely to point to valid memory. This would then cause a segfault when you dereference field in the loop. You were fortunate that you got such a clear sign that something was wrong -- memory errors aren't always so blatant.

Upvotes: 0

Arnaud Courtecuisse
Arnaud Courtecuisse

Reputation: 367

I actually simplified the code snippet. field_width was not initialzed. I'm surprised this did not raise a warning during the build. And I don't really know why it generates a segfault when x=0.

But my problem is solved. Thank you all and sorry for the conveniance...

Upvotes: 1

nick_w
nick_w

Reputation: 14938

Shouldn't it be this?

field = (char**)malloc(sizeof(char*)*field_width);

Edit

malloc can return null, so it would pay to check that field[x] = malloc(sizeof(char)*field_height); block of memory is valid.

Upvotes: 0

Science_Fiction
Science_Fiction

Reputation: 3433

field = (char*) malloc(sizeof(char*)*field_width);

The char* cast maybe?

Upvotes: 1

Related Questions