简体   繁体   English

如何使用C语言中的结构数组指针为结构分配内存?

[英]How to allocate memory for a structure with a pointer to an array of structures in C?

I have a function which create and return a new object for a list, but I'm having troubles with allocation of memory (Error: core dumped). 我有一个为列表创建并返回新对象的函数,但是我在分配内存时遇到了麻烦(错误:核心已转储)。 I figured it's because of '*model', which is a pointer to an array for structures. 我认为这是因为'* model',它是指向结构数组的指针。 I'm quite new to dynamic memory allocation and not sure what and how to allocate the right amount of memory. 我对动态内存分配还很陌生,不确定如何以及如何分配适当数量的内存。

Function: 功能:

// Return a newly created object based on the arguments provided. 
object_t *create_object(SDL_Surface *surface, triangle_t *model, int numtriangles)
{
    // Allocate memory for a new object
    object_t *new_obj = malloc(sizeof(object_t));
        if (new_obj == NULL)
            return NULL;
    // Allocate memory for the model array
    triangle_t *arrayPtr = malloc((sizeof(triangle_t))*numtriangles);
        if (arrayPtr == NULL)
            return NULL;

    // Assign values
    arrayPtr = model;
    new_obj->model = arrayPtr;
    new_obj->numtriangles = numtriangles;
    new_obj->surface = surface;
    // Return created object
    return new_obj;
}

Function call in main: 主函数调用:

object_t *ball = create_object(surface, sphere_model, SPHERE_NUMTRIANGLES);

Structures: 结构:

typedef struct object object_t;
struct object {
    float       scale;
    float       rotation;
    float       tx, ty;
    float       speedx, speedy;
    unsigned int ttl;          
    int         numtriangles;
    triangle_t  *model;
    SDL_Surface *surface;
};

typedef struct triangle triangle_t;
struct triangle {
    int x1, y1;
    int x2, y2;
    int x3, y3;
    unsigned int fillcolor;
    float scale;
    int tx, ty;
    float rotation;
    SDL_Rect rect;
    int sx1, sy1;
    int sx2, sy2;
    int sx3, sy3;
};

Array: 阵:

#define SPHERE_NUMTRIANGLES    478   // <-- Array size
triangle_t sphere_model[] = {
{
.x1=-1,
.y1=-500,
.x2=-1,
.y2=-489,
.x3=-1,
.y3=-500,
.fillcolor=0xeeeeee,
.scale=1.0
},
{
.x1=-1,
.y1=-489,
.x2=-1,
.y2=-500,
.x3=40,
.y3=-489,
.fillcolor=0xbb0000,
.scale=1.0
},
...

I tried object_t *new_obj = malloc(sizeof(object_t) + (sizeof(triangle_t)*numtriangles)); 我尝试了object_t *new_obj = malloc(sizeof(object_t) + (sizeof(triangle_t)*numtriangles)); but with no success. 但没有成功。

// Assign values
arrayPtr = model;

What you do here is discard newly allocated pointer contained in arrayPtr, and just assign it to point to the same memory as model . 您在这里要做的是丢弃arrayPtr中包含的新分配的指针,然后将其分配为指向与model相同的内存。 It might crash if model has shorter lifetime (eg allocated on stack) and is no longer valid pointer after function returns. 如果model生存期较短(例如,分配在堆栈上)并且在函数返回后不再是有效的指针,则可能会崩溃。

I believe your intention here was to copy content from model array into your new array, so you should have done something like: 我相信您的意图是copy内容从模型数组copy到新数组中,因此您应该执行以下操作:

memcpy(arrayPtr, model, (sizeof(triangle_t))*numtriangles);

So, looks like object_t *new_obj = malloc(sizeof(object_t) + (sizeof(triangle_t)*numtriangles)); 因此,看起来像object_t *new_obj = malloc(sizeof(object_t) + (sizeof(triangle_t)*numtriangles)); is an unnecessarily large allocation. 是不必要的大分配。

I say this because this line in the create_object method arrayPtr = model; 我之所以这样说,是因为create_object方法中的这一行arrayPtr = model; is assigning the memory address of the passed-in triangle_t* 'model', to the newly allocated arrayPtr. 正在将传入的triangle_t *'model'的内存地址分配给新分配的arrayPtr。

However, on the line above this you allocated a load of memory to the arrayPtr address... This would therefore lead to a memory leak as you are allocating the memory to that address, and then changing the address of the pointer (so it no longer points at that memory) but you aren't calling free on that memory, so it will sit on the heap for the duration of your program. 但是,在此行上方,您为arrayPtr地址分配了一个内存负载...因此,这将导致内存泄漏,因为您正在将内存分配给该地址,然后更改指针的地址(因此没有较长的指针指向内存),但您并未在该内存上调用free,因此它将在程序执行期间位于堆上。

With the line arrayPtr = model; 用行arrayPtr = model; I suspect what you actually want to do is perform a memory copy of the contents of the model address, to the newly allocated arrayPtr address. 我怀疑您实际上想要执行的操作是将模型地址内容的内存复制到新分配的arrayPtr地址。 This should therefore actually look like: 因此,实际上应该如下所示:

memcpy(arrayPtr, model, sizeof(triangle_t) * numTriangles);

Sadly I am unable to run your code as I am at work without access to a C compiler however, I would suspect that your error is caused by you free'ing the memory of the 'model' pointer that is still being accessed by the object_t struct due to the accidental misuse of the '=' assignment operator. 可悲的是,在无法访问C编译器的情况下,我无法在工作时运行您的代码,但是,我怀疑您的错误是由您释放仍由object_t访问的“模型”指针的内存引起的struct是由于意外误用了'='赋值运算符。

Thanks for the help. 谢谢您的帮助。 My thought process was to assign a pointer enough memory for the array, then make a copy of set array by assigning it to the pointer. 我的想法是为指针分配足够的内存用于数组,然后通过将其分配给指针来复制set数组。

Anyway, this did did the trick: 无论如何,这确实达到了目的:

new_obj->model = malloc(sizeof(triangle_t)*numtriangles);
    if (new_obj == NULL)
        return NULL;
bcopy(model, new_obj->model, sizeof(triangle_t)*numtriangles);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM