You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Raylib绘制对象数组时出现Segmentation Fault问题排查

问题:DrawObjects函数循环触发Segmentation Fault

我自定义了Object结构体,通过CreateObjects函数初始化创建带指定属性的对象数组,目的是把多个共用同一纹理的对象绘制到屏幕不同坐标。之前有过类似实现经验,这次逻辑几乎一致,但DrawObjects的绘制循环里一直触发Segmentation Fault。


相关代码

object.c

#include <malloc.h>
#include <stdio.h>
#include "raylib/include/raylib.h"
#include "object.h"

Object* CreateObjects(Texture2D texture, int numberOfObjects, int width, int height, double Xpos[], double Ypos[]){

        Object* objects = malloc(sizeof(Object) * numberOfObjects);

        for(int i=0; i < numberOfObjects; i++){
                objects[i].texture = texture;
                objects[i].rect.width = width;
                objects[i].rect.height = height;
                objects[i].rect.x = 0;
                objects[i].rect.y = 0;
                objects[i].position.x = Xpos[i];
                objects[i].position.y = Ypos[i];
        }
}

void DrawObjects(Object* objects, int numberOfObjects){

        for(int i=0; i < numberOfObjects; i++){
        DrawTextureRec(objects[i].texture, objects[i].rect, objects[i].position, WHITE);

        }
}

test.c 初始化代码

double objXPos[1] = {600-32};
double objYPos[1] = {900-64};
Texture2D barrelTexture = LoadTexture("sprites/barrel.png");
Object* barrels = CreateObjects(barrelTexture, 1, 64, 64, objXPos, objYPos);

test.c 绘制代码

BeginDrawing();
ClearBackground(BLACK);
DrawTexture(background, 0, 0, RAYWHITE);
DrawEntity(entity);
DrawObjects(barrels, 1);

if(bullet->isActive){
        DrawBullet(bullet);
        UpdateBullet(bullet);
        CheckEntityCollision(bullet, entity);
}

EndDrawing();

(注:DrawBullet和DrawEntity函数工作正常,问题大概率出在DrawObjects的循环部分)


问题分析与修复

核心问题

CreateObjects函数遗漏了返回语句!函数内用malloc分配了对象数组的内存,但最后没有return objects;,导致test.c中barrels变量拿到的是一个随机的无效地址。在DrawObjects中访问这个无效地址,直接触发Segmentation Fault。

修复后的CreateObjects函数

Object* CreateObjects(Texture2D texture, int numberOfObjects, int width, int height, double Xpos[], double Ypos[]){

        Object* objects = malloc(sizeof(Object) * numberOfObjects);
        // 可选:添加malloc失败的判断
        if (!objects) {
            fprintf(stderr, "malloc failed to allocate objects\n");
            return NULL;
        }

        for(int i=0; i < numberOfObjects; i++){
                objects[i].texture = texture;
                objects[i].rect.width = width;
                objects[i].rect.height = height;
                objects[i].rect.x = 0;
                objects[i].rect.y = 0;
                objects[i].position.x = Xpos[i];
                objects[i].position.y = Ypos[i];
        }
        // 添加返回语句
        return objects;
}

额外注意事项

  • 程序结束时记得调用free(barrels)释放内存,避免内存泄漏
  • 若添加了malloc失败判断,在调用CreateObjects后要检查返回值是否为NULL,避免后续操作空指针

内容的提问来源于stack exchange,提问作者d1zyz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 15:47:33