Allocating memory for nested structure pointer

放肆的年华 提交于 2019-12-13 02:48:28

问题


I am using a C code generator that is creating header files with following structures:

typdef struct Place {   
    struct Forest {
        int trees;
    } *Forest;
} Place ;

And using them in a c++ project.

When I try to access Place.Forest->trees, I get a segfault because Place.Forest is a dangling pointer.

I can't properly malloc it because Place.Forest = malloc(sizeof(Place.Forest)); will just return the size of the pointer.

I can't use Place.Forest=malloc(sizeof(struct Forest)); Because I am accessing Place from C++ and scoping prevents me from being able to see Forest.

How do I allocate memory for Forest without changing Place or un-nesting Forest?

Modifying the structures is impracticable due to the large amount of code that is being automatically generated.


回答1:


To allocate the memory for the Forest do like this.

 Place.Forest=malloc(sizeof(struct Forest));

It will allocate the memory as size of that structure.




回答2:


After several hours of screwing around, I found a solution.

You have to use extern C to get the compiler to use C style linking, but you also have to use C++'s scope resolution :: to correctly resolve the structure type.

header file:

#ifdef __cplusplus
extern "C" {
#endif

typdef struct Place {   
    struct Forest {
        int trees;
    } *Forest;
} Place ;

#ifdef __cplusplus
}
#endif

Program:

#include <stdlib.h>
#include <iostream>
extern "C" {      
    static void allocateForest(Place *p){
        p->Forest = (struct Place::Forest *)malloc(sizeof(struct Place::Forest));
    }
}

int main(void){
    Place p;
    allocateForest(&p);
    p.Forest->trees = 1;
    std::cout << p.Forest->trees << std::endl;
    return 0;
}



回答3:


Place.Forest = malloc(sizeof(Place.Forest));

should be

Place.Forest = malloc(sizeof(struct Forest));

Because as you see Forest is a pointer to your structure and sizeof(pointer) is not what you look for what you want is sizeof(struct Forest)




回答4:


In C, nested structs are visible through the whole program, so there's no point in nesting them. Just define them separately (and use typedefs so you don't have to write struct x every time:

typedef struct {
    int trees;
} Forest;

typedef struct {   
    Forest *forest;
} Place;

Now you can just write

malloc(sizeof(Forest));



回答5:


You should allocate memory to pointers otherwise they are NULL. Use this :

Place.Forest = (struct Forest*) malloc(sizeof(struct Forest));

One another thing : Don't name variables the name as typedefs.



来源:https://stackoverflow.com/questions/29293875/allocating-memory-for-nested-structure-pointer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!