Search code examples
carrayscharunsignedcalloc

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?


Solution

  • 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.