c - 读取较大的 .bmp 文件时出现段错误

标签 c memory-management segmentation-fault

编译时出现段错误。

当我尝试在 main() 中填充表数组时,我认为与第一个 for 循环中的内存分配有关?

如果我调用较小的文件但不使用“较大”的 table.bmp 文件,它会起作用。

我不明白为什么? (我对此很陌生)

任何帮助将不胜感激。

提前致谢

#include <stdio.h>
#include <string.h>
#include <malloc.h>

unsigned char *read_bmp(char *fname,int* _w, int* _h)
{
    unsigned char head[54];
    FILE *f = fopen(fname,"rb");

    // BMP header is 54 bytes
    fread(head, 1, 54, f);

int w = head[18] + ( ((int)head[19]) << 8) + ( ((int)head[20]) << 16) + ( ((int)head[21]) << 24);
int h = head[22] + ( ((int)head[23]) << 8) + ( ((int)head[24]) << 16) + ( ((int)head[25]) << 24);

// lines are aligned on 4-byte boundary
int lineSize = (w / 8 + (w / 8) % 4);
int fileSize = lineSize * h;

unsigned char *img = malloc(w * h), *data = malloc(fileSize);

// skip the header
fseek(f,54,SEEK_SET);

// skip palette - two rgb quads, 8 bytes
fseek(f, 8, SEEK_CUR);

// read data
fread(data,1,fileSize,f);



// decode bits
int i, j, k, rev_j;
for(j = 0, rev_j = h - 1; j < h ; j++, rev_j--) {
    for(i = 0 ; i < w / 8; i++) {
        int fpos = j * lineSize + i, pos = rev_j * w + i * 8;
        for(k = 0 ; k < 8 ; k++)
            img[pos + (7 - k)] = (data[fpos] >> k ) & 1;
    }`enter code here`
}

free(data);
*_w = w; *_h = h;
return img;
}

int main()
{

int w, h, i, j, x, y, b=0, butpos=0;

//Get array data

unsigned char* imgtable = read_bmp("table.bmp", &w, &h);
int table[w][h];

printf("w=%i \n", w);
printf("h=%i \n", h);

//make table array

 for(j = 0 ; j < h ; j++)
{

    for(i = 0 ; i < w ; i++)
        table[j][i] = imgtable[j * w + i] ? 0 : 1;

}

最佳答案

您正在尝试在堆栈上分配图像数据。当图像太大时,这会导致堆栈溢出。这段代码有问题:

int main()
{

    int w, h, i, j, x, y, b=0, butpos=0;

    //Get array data

    unsigned char* imgtable = read_bmp("table.bmp", &w, &h);
    int table[w][h];  // <-- HERE
    ...

这使用了 C99 的一项名为可变长度数组 (VLA) 的功能,其中一个非恒定大小的数组(在本例中为 2D w h 数组,其中 wh 直到运行时才知道)在堆栈上分配。

在堆栈跟踪中提到函数 _alloca 应该会提示您这一点 - alloca(3)函数在堆栈上分配动态数量的内存。而且由于您自己没有在任何地方显式调用 alloc(),因此它一定来自 VLA 的使用。

正如您提到的,修复方法是在堆上分配图像数据,而不是在堆栈上:

data = malloc(h * w * sizeof(*data));
table = malloc(h * sizeof(*table));
for (i = 0; i < h; i++)
{
    table[i] = &data[i * w];
}

...

free(table);
free(data);

关于c - 读取较大的 .bmp 文件时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15997552/

相关文章:

c - 程序运行正常,但逻辑运算符在 C 中无法正常工作

matlab - 在matlab中有效利用GPU内存

c++ - std::stoi 导致段错误

c++ GMP mpz_init() 导致段错误 11

c - 在 C 编程中存储日志/错误消息

C++ - 共享指针数组

c - 在不使用任何运算符的情况下求两个数字的总和

Java - 使用 Swing 框架和抽象类防止 Java 堆内存错误

Python 列表/字典与 numpy 数组 : performance vs. 内存控制

python - 我如何处理追溯到杀死我的 worker 的段错误?