charlesw
charlesw

Reputation: 612

Allocating memory for nested structure pointer

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.

Upvotes: 0

Views: 1230

Answers (5)

user4710450
user4710450

Reputation:

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.

Upvotes: 0

charlesw
charlesw

Reputation: 612

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;
}

Upvotes: 1

EMBLEM
EMBLEM

Reputation: 2265

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));

Upvotes: 0

Karthikeyan.R.S
Karthikeyan.R.S

Reputation: 4051

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.

Upvotes: 1

Gopi
Gopi

Reputation: 19874

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)

Upvotes: 0

Related Questions