【发布时间】:2016-02-09 15:55:51
【问题描述】:
我一直在尝试为 bmp 文件动态分配内存。我之前使用的是常量值,它工作得很好,但是当我尝试从另一篇文章中实现代码时: C Programming: malloc() inside another function 我正在尝试为具有 RGB 值的 bmp 的每个内存位置分配。
我收到分段错误(核心转储)错误。
谁能告诉我我做错了什么?
int main(){
unsigned char **pixels;
scanf("%d %d", &picHeight, &picWidth);
// dynamically allocate memory for height and width.
pixels = malloc(picHeight * sizeof *pixels);
int i;
for ( i = 0; i < picHeight * 3; i+=3) {
pixels[i] = malloc(picWidth * sizeof *pixels[i]);
pixels[i+1] = malloc(picWidth * sizeof *pixels[i]);
pixels[i+2] = malloc(picWidth * sizeof *pixels[i]);
}
fread( header, 1 , HEADER_SIZE , inputfile1);
fread( pixels, 1 , picHeight * picWidth * 3 , inputfile1);
darken(pixels, picHeight, picWidth);
fclose(inputfile1);
fclose(outputfile1);
return 0;
}
void darken(unsigned char** pixels, int picHeight, int picWidth) {
int r,c;
for( r = 0; r < picHeight; r++) {
for ( c = 0; c < picWidth * 3; c += 3) {
int temp1 = pixels[r][c];
int temp2 = pixels[r][c+1];
int temp3 = pixels[r][c+2];
temp1 = temp1 - 50;
temp2 = temp2 - 50;
temp3 = temp3 - 50;
if(temp1 < 0) temp1 = 0;
if(temp2 < 0) temp2 = 0;
if(temp3 < 0) temp3 = 0;
pixels[r][c] = temp1;
pixels[r][c+1] = temp2;
pixels[r][c+2] = temp3;
}
}
fwrite( header, sizeof(char) , HEADER_SIZE , outputfile1);
fwrite( pixels, sizeof(char) , picHeight * picWidth * 3 , outputfile1);
}
完整的代码真的很长,所以我不想全部包含在内。
【问题讨论】:
-
提供minimal reproducible example。您的代码中没有二维数组。
-
在循环中一次分配三个而不是一次分配一个是否有原因?无论如何,
i < picHeight * 3是行不通的。你只分配了picHeight指针,pixels[picHeight ... 3 * picHeight - 1]访问未分配的内存。最后但同样重要的是,指针不是数组也不是指针:你有一个指向指针的指针,而不是二维数组。 -
您的调试器会告诉您在哪里发生崩溃。
-
我在 gedit 中运行 ubuntu 我没有用于此类的调试器。