user3055867
user3055867

Reputation: 17

Segmentation fault in 2D array unsigned char using calloc in C

I've trying to allocate an unsigned char** using calloc:

newmatriz = (unsigned char**) calloc(width, sizeof(unsigned char));

for (j=0 ; j < width; j++)
{
    if (newmatriz[j]=(unsigned char*)calloc(witdh, sizeof(unsigned char)) == NULL){
        printf("Memory allocation error. Exit program\n");
        exit(1);
    }
}

for (i=0;i<width;i++)
{
    for(j=0;j<width;j++)
    {
        newmatriz[i][j] = 0;
    }
}

But I get segmentation fault when I'm trying to acces the pos [i][j]

Is problem be related to the use int as iterator?

Upvotes: 1

Views: 684

Answers (3)

Ingo Leonhardt
Ingo Leonhardt

Reputation: 9904

In the second calloc() there are some brackets missing:

if (newmatriz[j] = calloc(witdh, sizeof(unsigned char)) == NULL){

should be

if ((newmatriz[j] = calloc(witdh, sizeof(unsigned char))) == NULL){

Without that, calloc()s result is compared with NULL and the result of the comparison instead of the pointer is stored in newmatriz[j]

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 311068

There is a typo in this statement. Instead of sizeof( unsigned char ) you have to use sizeof( unsigned char * )

newmatriz = (unsigned char**) calloc(width, sizeof(unsigned char *));
                                                            ^^^^^^

Also this if statement is incorrect

if ( newmatriz[j] = calloc(witdh, sizeof(unsigned char) ) == NULL){

In this statement newmatriz[j] is set either to 1 or 0 depending on whether the memory allocation was successfull or not.

I think you mean

if ( ( newmatriz[j] = calloc(witdh, sizeof(unsigned char) ) ) == NULL){

And these loops

for (i=0;i<width;i++)
{
    for(j=0;j<width;j++)
    {
        newmatriz[i][j] = 0;
    }
}

do not make sense because calloc already initialized the allocated memory by zeroes.

Upvotes: 2

ceorron
ceorron

Reputation: 1268

The answer is simple newmatriz is an array (aka pointer) to unsigned char* you are allocation unsigned char simply change the top line to allocate the correctly sized array, in this case you want an array of byte size width*sizeof(unsigned char*) not width*sizeof(unsigned char) as you currently have it.

newmatriz = (unsigned char**) calloc(width, sizeof(unsigned char*));
for (j=0 ; j < width; j++){
    if (newmatriz[j]=(unsigned char*)calloc(witdh, sizeof(unsigned char)) == NULL){
       printf("Memory allocation error. Exit program\n");
        exit(1);
    }
}

Upvotes: 1

Related Questions