我遇到了一个奇怪的分段错误:当我使用 gcc -std=gnu90 运行这个 C 文件时出现 11 错误。从我读到的内容来看,我的代码中的某个地方超出了内存?但是,在进行了大量调试之后,我不确定它在哪里超过。对于一个小的 bmp 文件,我将高度和宽度分别指定为 160 和 240。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void brighten(int,int,char*);
//void contrast(int height, int width, char* file);
//void rotation(int height, int width, char* file);
#define HEADER_SIZE 54
int main(void) {
printf("Enter the filename: ");
char file[256];
scanf("%s", file);
printf("Enter the height and width (in pixels): ");
int height, width;
scanf("%d %d",&height,&width);
strcat(file,".bmp");
brighten(height,width,file);
//contrast(height,width,file);
//rotation(height,width,file);
return 0;
}
void brighten(int height, int width, char* file) {
FILE *input = fopen(file,"rb");
FILE *output = fopen("copy1.bmp","wb");
char header[HEADER_SIZE];
unsigned char pixels[height][width * 3];
fread(header,1,HEADER_SIZE,input);
fread(pixels,1,height * width * 3,input);
int r, c;
for( r = 0; r < height; r++) {
for(c = 0; c < width * 3; c++) {
pixels[r][c] += 50;
if( pixels[r][c] > 255) {
pixels[r][c] = 255;
}
printf(" %c n",pixels[r][c]);
}
}
fwrite(header,sizeof(char), HEADER_SIZE,output);
fwrite(pixels,sizeof(char),height * width * 3, output);
fclose(input);
fclose(output);
}
正如@Chris所评论的那样,您应该检查fopen()
是否返回NULL
。对NULL
指针执行读/写操作会导致分段错误。
根据 GNU C 库手册:
如果打开失败,
fopen()
将返回空指针。
fopen()
可能由于各种原因(但不限于)而赋予NULL
价值:
- 文件不存在
- 没有文件所需的权限
建议检查errno,以防fopen()
返回NULL
。