c - 使用 SDL_image 保存 PNG 时出现段错误
问题描述
我必须使用 SDL2 和 SLD2_image 在 C 中创建 OCR。
在 macOS 上一切正常。但是,在 Linux 上运行我的程序时,我在保存 PNG 文件时遇到了段错误。
我尝试更新我使用的库(SDL2、SDL2_image 和 libpng),但只能保存黑色图像并在 IMG_QUIT() 或 SDL_QUIT() 上出现段错误
所以我的代码在IMG_SavePNG(surface, "textmono.png")
我也试过
SDL_SaveBMP(surface, "textmono.bmp")
并得到了相同的结果...
所以这是我的代码:
void BlackAndWhite(SDL_Surface* surface){
Uint32 *pixels = (Uint32 *)surface->pixels;
for(int i = 0; i < surface->h; i++){
for(int j = 0; j < surface->w;j++){
Uint8 red = 0;
Uint8 green = 0;
Uint8 blue = 0;
SDL_GetRGB(pixels[i*surface->w + j], surface->format, &red, &green, &blue);
Uint8 black = (red + green + blue)/3;
pixels[i*surface->w + j] = SDL_MapRGB(surface->format, black, black, black);
}
}
IMG_SavePNG(surface, "textbw.png");
}
这里是我如何加载我的 png 文件:
int loadimage(void){
if(SDL_Init(SDL_INIT_VIDEO)==-1)
{
printf("SDL_Init: %s\n", SDL_GetError());
return 1;
}
IMG_Init(~0);
SDL_Surface *surface = IMG_Load("text.png");
if(surface != NULL){
...
}
else{
printf("Failed ! %s\n", IMG_GetError());
}
return 0;
}
GDB 给了我这个:
Thread 1 "main" received signal SIGSEGV, Segmentation fault.
0x00007ffff7cc947d in _int_malloc (av=av@entry=0x7ffff7e16c40 <main_arena>,
bytes=bytes@entry=1304) at malloc.c:3880
3880 malloc.c: Aucun fichier ou dossier de ce type.
(gdb) where
0x00007ffff7cc947d in _int_malloc (
av=av@entry=0x7ffff7e16c40 <main_arena>, bytes=bytes@entry=1304)
at malloc.c:3880
0x00007ffff7ccacaa in __GI___libc_malloc (bytes=1304) at malloc.c:3073
0x00007ffff3894e74 in png_malloc_warn ()
from /lib/x86_64-linux-gnu/libpng16.so.16
0x00007ffff388ec41 in ?? () from /lib/x86_64-linux-gnu/libpng16.so.16
0x00007ffff38ab88e in png_create_write_struct_2 ()
from /lib/x86_64-linux-gnu/libpng16.so.16
0x00007ffff38ab931 in png_create_write_struct ()
from /lib/x86_64-linux-gnu/libpng16.so.16
0x00007ffff7e47d88 in IMG_SavePNG_RW_libpng (surface=0x5555558c9f00,
dst=0x5555557fca40, freedst=1) at IMG_png.c:544
0x000055555555531f in BlackAndWhite (surface=0x5555558c9f00) at main.c:60
0x00005555555554d0 in loadimage () at main.c:38
0x0000555555555116 in main () at main.c:21
编辑:AddressSanitizer 告诉我,有一个堆缓冲区溢出
SDL_GetRGB(pixels[i*surface->w + j], surface->format, &red, &green, &blue)
删除这部分代码确实解决了问题,所以我想我找到了问题,但我真的不明白这一行有什么问题......
解决方案
推荐阅读
- python - USB 网络摄像头不再适用于 opencv:VIDIOC_QBUF: Invalid Argument
- discord.js - 如何让不和谐 oauth2 加入不和谐服务器
- typescript - 键入复合函数的正确方法是什么?
- performance - 以下嵌套循环中第二个 for 循环的时间复杂度是多少?
- unix - 查找在同一行上多次出现模式的文件
- javascript - 用java脚本添加零小数
- amazon-web-services - EventType:查看器请求导致 503 的 lambda 边缘
- c++ - 如何使用 boost/beast 从 HTTP POST 请求中解析和提取有效负载?
- julia - 在 Julia 中初始化任何变量
- nestjs - 如何在 NestJS 上测试具有多个守卫的控制器