[英]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.