简体   繁体   English

使用C语言中的calloc在2D数组unsigned char中进行分段错误

[英]Segmentation fault in 2D array unsigned char using calloc in C

I've trying to allocate an unsigned char** using calloc : 我试图使用calloc分配一个unsigned char**

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] 但是当我试图访问pos [i] [j]时,我得到了分段错误

Is problem be related to the use int as iterator? 问题与使用int作为迭代器有关吗?

There is a typo in this statement. 这句话中有一个拼写错误。 Instead of sizeof( unsigned char ) you have to use sizeof( unsigned char * ) 而不是sizeof( unsigned char )你必须使用sizeof( unsigned char * )

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

Also this if statement is incorrect 此if语句也是错误的

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. 在此语句中, newmatriz[j]被设置为1或0,具体取决于内存分配是否成功。

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. 没有意义,因为calloc已经用零初始化了分配的内存。

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 *你是分配unsigned char只需改变顶行来分配正确大小的数组,在这种情况下你需要一个字节大小width*sizeof(unsigned char*)的数组width*sizeof(unsigned char*)不是你现在拥有的width*sizeof(unsigned char)

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);
    }
}

In the second calloc() there are some brackets missing: 在第二个calloc()有一些括号丢失:

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] 没有它, calloc()的结果与NULL进行比较,而比较的结果而不是指针存储在newmatriz[j]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM