我不想重新发明轮子,所以我下载了libtga,它似乎有一个方便而简单的API。建筑很容易,但我偶然发现了一个我无法解释的奇怪的分段错误。一个小例子:
#include <stdio.h>
#include "tga.h"
#define TEST
int main()
{
TGA *tga;
TGAData data;
tga = TGAOpen("test.tga", "r");
if(!tga || tga->last != TGA_OK)
{ printf("TGAOpen failed\n"); return 1; }
if(TGAReadImage(tga, &data) != TGA_OK)
{ printf("TGAReadImage failed\n"); return 1; }
TGAHeader *header = &tga->hdr;
printf("image dimensions:\n width: %d\t height:%d\t depth:%d bpp\n",
header->width, header->height, header->depth);
tbyte *img = data.img_data;
if (img== NULL)
{
printf("Pointer wrong\n");
return 1;
}
printf("pointer: %p\n", img);
printf("test %hhu\n", img[0]);
#ifdef TEST
for(int i=0; i<header->height; i++)
{
for(int j=0; j<header->width; j++)
{
int index = 4*(i*header->width + j);
printf("%3d %3d %3d %3d | ", img[index], img[index+1], img[index+2], img[index+3]);
}
printf("\n");
}
#endif
TGAClose(tga);
return 0;
}
我用以下代码编译程序:gcc -g --std = c99 -O0 tgatest.c -L./lib -ltga -I./include
现在,如果&#34; TEST&#34;定义一切正常,每个像素的值打印到stdout(我使用4x4图像)。如果我没有定义&#34; TEST&#34;它会在行
处引发分段错误printf("test %hhu\n", img[0]);
我不明白为什么。调试显示&#34; img&#34;是&#34;地址0x1越界&#34;,但是 &#34; TEST&#34;这是一个有效的地址。有什么建议如何进一步调查这个?我认为编译器可能会优化掉东西,但是-O0并没有改变任何东西。对于--std = c99也是如此。
答案 0 :(得分:3)
根据tgalib documentation,您需要在调用TGA_IMAGE_DATA
之前在data->flags
设置TGAReadImage
,以确保能够读取图像数据。可能的是,在TEST构建中,数据变量下的堆栈上的垃圾恰好设置了这个位,而不是在其他构建中。
在TGAReadImage
调用之前立即添加如下所示的行应该可以解决问题:
data.flags = TGA_IMAGE_DATA;