Hi I have a struct like this
struct small_struct {
int a;
int b;
}
struct big_struct {
struct *small_struct child;
}
I want to pass the pointer of big_struct
as a parameter into a function in which child
is initialized.
static int my_function(struct big_struct* s) {
if (certain_condition)
s->child = &(struct small_struct) {
.a = 1;
.b = 2;
}
}
However, when I do this and my_function
is finished, the fields in s->child
are often changed outside of the my_function
. Would there be a way to keep a
and b
values as it was initialized inside my_function
?
Thank you!
CodePudding user response:
The problem is here:
s->child = &(struct small_struct) {
.a = 1;
.b = 2;
}
This creates the struct in the stack memory of the function, then assigns the s->child
pointer to that memory. As soon as the function returns, that memory is no longer allocated to your struct. What you need to do is allocate heap memory for the structure, using malloc
, which will stay allocated until it is free'd with a call to free
:
static int my_function(struct big_struct* s) {
if (certain_condition)
{
//Allocate *heap* memory for the pointer
//This must be freed later!
//e.g free(s.child);
s->child = malloc(sizeof(struct small_struct));
s->child->a = 1;
s->child->b = 2;
}
Alternatively, depending on what you are trying to do, don't make child
a pointer, that way the memory is already allocated in the instance of big_struct
e.g.:
struct big_struct
{
struct small_struct child; //Note: not a pointer
};
static int my_function(struct big_struct* s) {
if (certain_condition)
{
//Memory for child member is already allocated
s->child.a = 1;
s->child.b = 2;
}
}