c - 读取位置位置 0x1D5C4C2F 访问冲突

标签 c memory rgb

该函数在读取原始像素值时引发访问冲突,我不明白为什么。 可以将其视为我正在运行的代码的唯一部分,我已经单独运行了此代码并得到了相同的结果。

string filenames[]={"firstclick.raw", "secondclick.raw","thirdclick.raw","fourthclick.raw","fifthclick.raw","sixthclick.raw","seventhclick.raw","eighthclick.raw"};
FILE *file;
int height= 750, width = 453, bbp=3;

unsigned char ****images;
images = (unsigned char ****)malloc(sizeof(unsigned char ***)*8);
for(int j = 0; j<8; j++){
    images[j] = (unsigned char ***)malloc(sizeof(unsigned char**)*height);
    for(int i = 0; i<height; i++){
        images[j][i]= (unsigned char **)malloc(sizeof(unsigned char*)*width);
        for(int k = 0; k<bbp; k++)
            images[j][i][k]= (unsigned char *)malloc(sizeof(unsigned char)*bbp);
    }
}

for (int i = 0; i<8; i++){
    if (!(file=fopen(filenames[i].c_str(),"rb"))){
        cout << "Cannot open file: "<<filenames[i].c_str() <<endl;
        exit(1);
    }
    fread(images[i], sizeof(unsigned char), height*width*bbp, file);
    fclose(file);
}

最佳答案

这里的问题是您已将数组的每个元素分配为单独的数组(内存中的其他位置,其位置保留为指针)。但是当您读入时,您会假设它是一个连续的 block 。您将覆盖所有这些指针,并溢出缓冲区以启动。

如果您希望图像成为一组离散的内存块,请像这样分配:

unsigned char ** images;
int i;

images = malloc( sizeof(unsigned char *) * 8 );
for( i = 0; i < 8; i++ ) {
    images[i] = malloc( width * height * bpp );
}

请注意,sizeof(unsigned char) 由标准定义为始终为 1。您无需始终乘以 sizeof(unsigned char) .

现在,要获取图像中的像素地址,您需要相乘(通常是行优先):

unsigned char * pixel = images[i] + (y * width + x) * bpp;
unsigned char r = pixel[0];
unsigned char g = pixel[1];
unsigned char b = pixel[2];

关于c - 读取位置位置 0x1D5C4C2F 访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18906576/

相关文章:

c - C Unix 中的段错误(核心转储)

c - 如何使用 fscanf 在 C 中读取 double

c++ - 即使标题正确,也没有什么不起作用? (GCC C++)

matlab - 如何在 RGB 空间中表示来自 PCA 空间的点

c - 将 ptrdiff_t 的正值分配给 size_t 是否安全

c - 链接器脚本不起作用?

c - Linux,bash 脚本内存不足,无法交互,不是 ulimit?

linux - shmget() 返回带有 IPC_CREAT 的 ENOENT

ios - 从 UIColor 中提取 RGB 值

image - rawvideo 和 rgb32 值传递给 FFmpeg