[英]libtga weird Segmentation fault
我不想重新發明輪子,所以我下載了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
現在,如果定義了“ TEST”,一切正常,並且每個像素的值都打印到stdout(我使用4x4圖像)。 如果我未定義“ TEST”,則會在行上引發細分錯誤
printf("test %hhu\n", img[0]);
我不明白為什么。 調試顯示“ img”是“地址0x1超出范圍”,但使用“ TEST”則是有效地址。 有什么建議如何進一步調查嗎? 我以為編譯器可以優化一些東西,但是-O0不會改變任何東西。 與--std = c99相同。
根據tgalib文檔 ,在調用TGAReadImage
以確保將讀取圖像數據之前,需要在data->flags
上設置TGA_IMAGE_DATA
。 在TEST構建中,有可能在data變量下的堆棧上的垃圾恰好設置了此位,而在其他構建中則沒有。
緊接在TGAReadImage
調用之前添加如下TGAReadImage
:
data.flags = TGA_IMAGE_DATA;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.