[英]libtga weird Segmentation fault
I didn't want to reinvent the wheel, so I downloaded libtga which seemed to have a convenient and simple API. 我不想重新发明轮子,所以我下载了libtga ,它似乎具有一个便捷的API。 Building was easy, but I stumbled upon a weird segmentation fault I can not explain.
构建过程很容易,但是我偶然发现了一个我无法解释的奇怪的细分错误。 A small example:
一个小例子:
#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;
}
I compile the program with: gcc -g --std=c99 -O0 tgatest.c -L./lib -ltga -I./include 我用以下命令编译程序:gcc -g --std = c99 -O0 tgatest.c -L./lib -ltga -I./include
Now, if "TEST" is defined everything works fine and the values for each pixel are printed to stdout (I use a 4x4 image). 现在,如果定义了“ TEST”,一切正常,并且每个像素的值都打印到stdout(我使用4x4图像)。 If I don't define "TEST" it throws a segmentation fault at line
如果我未定义“ TEST”,则会在行上引发细分错误
printf("test %hhu\n", img[0]);
I don't understand why. 我不明白为什么。 Debugging shows that "img" is "Address 0x1 out of bounds", but with "TEST" it is a valid address.
调试显示“ img”是“地址0x1超出范围”,但使用“ TEST”则是有效地址。 Any suggestions how to further investigate this?
有什么建议如何进一步调查吗? I thought the compiler may optimize things away, but -O0 doesn't change anything.
我以为编译器可以优化一些东西,但是-O0不会改变任何东西。 Same for the --std=c99.
与--std = c99相同。
According to the tgalib documentation you need to set TGA_IMAGE_DATA
on data->flags
before calling TGAReadImage
to ensure that the image data will be read. 根据tgalib文档 ,在调用
TGAReadImage
以确保将读取图像数据之前,需要在data->flags
上设置TGA_IMAGE_DATA
。 It's possible that in the TEST build the garbage on the stack under the data variable happens to have this bit set, but not in the other build. 在TEST构建中,有可能在data变量下的堆栈上的垃圾恰好设置了此位,而在其他构建中则没有。
Adding a line like the following immediately before the TGAReadImage
call should do the trick: 紧接在
TGAReadImage
调用之前添加如下TGAReadImage
:
data.flags = TGA_IMAGE_DATA;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.