this thread is the closest I found, so I'll post here although it's years old. If it's preferable to open a new thread, please make it so, or let me know and I'll do it myself. So my problem is as follows:
I have an algorithm that uses a struct many times. It's inneficient to allocate and kill inside the loop, so I wanted a couple of functions to allocate and free the complicated structure; why is it complicated? well because the struct has pointers to double inside, instead of the actual memory. this is good cause the same structure can point to repeated double stuff ELSEWERE. The bottom line, is I need to work with these chained structs:
Code:
typedef struct {
void *contstate;
void *discstate;
REAL *rcontstate;
int indexdiscstate;
} contdiscstate;
typedef struct {
int option;
REAL t;
REAL *delta;
REAL *u;
int indexdiscstate;
} cddiscstate_d;
so what I need, is an allocating function like this one:
Code:
void *cdstatealloc_d(const void *params)
{
const cdstaparams_d *pa=params;
int noptions=(*pa).noptions;
contdiscstate *cds=malloc(sizeof(contdiscstate));
(*cds).discstate=malloc(sizeof(cddiscstate_d));
cddiscstate_d *ds=(*cds).discstate;
(*ds).delta=malloc(sizeof(REAL)*noptions);
(*ds).u=malloc(sizeof(REAL)*noptions);
return (void *) cds;
}
I made the function return a pointer so that I wouldn't have to use double pointers, cause later I can do something like:
void *state=statealloc(params);
the freeing function looks like:
Code:
int cdstatefree_d(void *state, const void *params)
{
contdiscstate *cds=state;
cddiscstate_d *ds=(*cds).discstate;
free((*ds).delta);
free((*ds).u);
free((*cds).discstate);
free(cds);
return 0;
}
this last one gives me a segmentation fault at "free((*ds).delta);" I thought since the pointer is stored deep inside, that it would remember what the memory is and be able to let it go, but it seems that somehow (*ds).delta is not the pointer I need to free the mem I allocated in the other function.
I understand how convoluted this looks, but the program is complicated, and I have given quite a bit of thought to this nested structures and so, there is no simple way to get rid of that. If someone could help me with this, I would greatly appreciate it.