c-在其他文件中的结构/数组上使用malloc



UPDATE:分段故障的问题不在下面描述的这个函数内,而是在同一程序的另一个函数内

我正在尝试制作一个动画弹球的程序,但我很困,无法弄清楚我做错了什么。我相信我已经将问题隔离在下面的函数中。我已经发现这与新的模型语句有关。

无论如何,在运行代码时,我会出现分段错误,函数绘制的值(以三角形表示(远远超出了它们应该的位置。我应该得到0到1600之间的值,但有时我会得到9400万。

非常感谢您的帮助!

object_t *create_object(SDL_Surface *surface, triangle_t *model, int numtriangles){
    object_t *new=malloc(sizeof(object_t));
    new->surface = surface;
    new->model = malloc(sizeof(triangle_t)*numtriangles);
    *new->model= *model;
    new->numtriangles = numtriangles;
    new->tx = surface->w/2;
    new->ty = surface->h/2;
    new->scale = 0.1;
    new->rotation = 0.0;
    
    return new;
}

NB!triangle_t*模型指针指向一个描述多个三角形的数组。

编辑:包括对象的结构体:

typedef struct object object_t;
struct object {
       float       scale;          /* Object scale */
       float       rotation;       /* Object rotation */
       float       tx, ty;         /* Position on screen */
       float       speedx, speedy; /* Object speed in x and y direction */
       unsigned int ttl;           /* Time till object should be removed from screen */
       int         numtriangles;   /* Number of triangles in model */
       triangle_t  *model;         /* Model triangle array */
       SDL_Surface *surface;       /* SDL screen */
};

三角形的结构:

typedef struct triangle triangle_t;
struct triangle {
    /* Model coordinates, where each pair resemble a corner  */
    int x1, y1;
    int x2, y2;
    int x3, y3;
    /* The color the triangle is to be filled with */
    unsigned int fillcolor;
    /* Scale factor, meaning 0.5 should half the size, 1 keep, and 2.0 double */
    float scale;
    /* The point (tx, ty) where the center of the teapot should be placed on-screen */
    int tx, ty;
    /* The degrees the triangle is supposed to be rotated at the current frame */
    float rotation;
    /* 
     * Bounding box of on-screen coordinates:
     * rect.x - x-coordinate of the bounding box' top left corner
     * rect.y - y-coordinate of the bounding box' top left corner
     * rect.w - width of the bounding box
     * rect.h - height of the bounding box
     */
     SDL_Rect rect;
    /* On-screen coordinates, where each pair resemble a corner */
    int sx1, sy1;
    int sx2, sy2;
    int sx3, sy3;
};

此行只复制第一个三角形:

*new->model = *model;

从函数的角度来看,model只是一个指向对象的指针。编译器不知道它指向一个三角形数组,因此我们需要将其中的三角形数量作为参数传递。

替换为:

memcpy( new->model, model, sizeof(triangle_t)*numtriangles);

附加评论:

  • 释放object时请记住释放model
  • 如果您考虑使用c++编译器编译new,请将其替换为类似newObj的其他内容

更多信息:

  • https://linux.die.net/man/3/memcpy
  • https://en.cppreference.com/w/c/string/byte/memcpy

[EDIT]关于分段错误:你的函数现在是正确的,它不会导致SEGFAULT,除非你的内存不足,这是非常不可能的。无论如何,如果你的内存不足,并且在该函数中得到SEGFAULT,那么问题是:

  • 您没有在其他地方正确释放内存,然后出现内存泄漏,导致内存不足
  • 你的平台需要更多的内存——尽管不太可能,但这是可能的——尤其是如果它是一个有限的嵌入式平台

发布另一个带有segfault回溯的问题。

最新更新