pedrrrib
pedrrrib

Reputation: 43

Struct with 2d array segmentation fault's on writing

I have been having trouble with this function the past day, and scouring similar questions in the website did not help.

I am trying to initialize a struct which contains a 2d array. As is, the program compiles fine and has no problem reading from the array, but causes a segmentation fault every-time it tries to write to the array.

This is the structure in question:

typedef struct {
    pgm_format_t format;
    unsigned int width;
    unsigned int height;
    unsigned int block_width;
    unsigned int block_height;
    unsigned int max_value;
    unsigned short **blocks;
} cod_t;

And this is the function:

cod_t cod_create(pgm_format_t format, unsigned int width, unsigned int height){

cod_t cod;
unsigned short i;

if((cod.blocks=calloc(width,sizeof(unsigned short *)))==NULL){

printf("nope 1\n"); //no problem
}

for(i=0;i<width;i++){
    if((cod.blocks[width]=calloc(height,sizeof(unsigned short)))==NULL){
        printf("nope 2\n"); //no problem
    }
}
int f=cod.blocks[0][0]; //no problem
printf("%d",f); //writes a wierd number, probably because it's never been assigned

cod.blocks[0][0]=3; //segmentation fault
printf("%d",cod.blocks[0][0]);

return cod;
}

What am I doing wrong here?

EDIT:

Ok, it appears I made a newbie mistake in the second calloc. however, even with

    if((cod.blocks[i]=calloc(height,sizeof(unsigned short)))==NULL){

the second printf prints something other than 3 (in my case, 031280), so there is something still wrong about this.

There is no segmentation fault now though (not in this part of the program at least, though there is one further away, when it tries to write several numbers to the array).

Upvotes: 1

Views: 52

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409196

Take a look at your "inner" allocation again, where you assign to cod.blocks[width], which is out of bounds and will lead to undefined behavior.

I'm sure you mean to assign to cod.blocks[i] there.

Upvotes: 1

Related Questions