[英]SDL_CreateTextureFromSurface crashes after using strcpy, strcat, sprintf, etc. in C
我想在屏幕上写一些文字。 为此,我正在使用以下代码:
TTF_Font* font = TTF_OpenFont("arial.ttf", 15);
SDL_Color text_color = { 255, 255, 255 };
SDL_Surface* text_surface = TTF_RenderText_Blended_Wrapped(font, "inventory", text_color, 100);
SDL_Texture* text_texture = SDL_CreateTextureFromSurface(rend, text_surface);
我在这下面还有一些其他的东西,但这没关系。 重点是这行得通。 现在我不想一直说“库存”,而是想要一个字符串来控制它。 这是我在上面的代码之前放的:
char inv_string[] = "";
char items[15][10] = { "air", "cloud", "water", "wood ", "leaves ", "in_cave", "grass ", "dirt ", "stone ", "coal ", "iron ", "gold ", "diamond", "player" };
if (item_count <= 0) strcpy(inv_string, "your inventory is empty\n");
if (item_count > 0) sprintf(inv_string, "> %s %d <", items[inventory->item], inventory->amount);
if (item_count > 1) sprintf(inv_string + strlen(inv_string), " %s %d\n", items[inventory->next->item], inventory->next->amount);
if (item_count > 2) sprintf(inv_string + strlen(inv_string), " %s %d\n", items[inventory->next->next->item], inventory->next->next->amount);
if (item_count > 3) sprintf(inv_string + strlen(inv_string), " %s %d\n", items[inventory->next->next->next->item], inventory->next->next->next->amount);
if (item_count > 4) sprintf(inv_string + strlen(inv_string), " %s %d\n", items[inventory->next->next->next->next->item], inventory->next->next->next->next->amount);
for (unsigned int i = 5 - item_count; i > 0; i--) sprintf(inv_string + strlen(inv_string), " empty\n");
该字符串包含我需要的内容。 但是现在即使没有用inv_string
替换"inventory"
,我在 SDL_CreateTextureFromSurface 也会遇到访问冲突错误。 有人能告诉我为什么会发生这种情况以及如何解决吗? 提前致谢,祝您有美好的一天!
该声明
strcpy(inv_string, "your inventory is empty\n");
将导致未定义的行为,因为 memory 缓冲区inv_string
只有一个字节的空间。 但是,需要 25 个字节的大小来存储整个字符串,包括终止 null 字符。 这会导致缓冲区溢出。
对sprintf
的 function 调用有同样的问题,因为它们还要求缓冲区大小大于单个字节。
最明显的解决方案是增加inv_string
的大小,例如:
char inv_string[200] = "";
另一种方法是改用动态 memory 分配。 你可以换行
char inv_string[] = "";
至
char *inv_string;
然后使用 malloc 使该指针指向一定大小的已分配malloc
。 如果您稍后确定需要更大的 memory 块,您可以使用realloc
请求更多的 memory。
If you find the memory management of strings too tedious and complicated in C, then you might want to consider writing your program in C++ instead of C. std::string
C++ class 为您处理字符串的 memory 管理。
我设法修复了它,其中一部分是你们指出的,所以谢谢,另一件事是 SDL 无法找到字体文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.