I have two a structure for which I have created two instances of structure using pointer to struct and I am expecting them to return two different values based on the input . If I execute this code in visual studio code , I see the int_struct_pt1 and int_struct_pt2 has the same addresses in the memory . So when int_struct_pt2 receives it value int_struct_pt1 is overwritten by the same value of int_struct_pt2.
I am working on STM32F4 , so I do not want to use the dynamic memory allocation . Is there any other way I can get these data without being overwritten or how do I handle the memory allocation .
//int_struct.h
//Declaration in header file
typedef struct {
int a;
int b;
} int_struct;
int_struct * func(int a);
//int_app.c
//Pointer to struct in source file
static int_struct* int_struct_pt1;
static int_struct* int_struct_pt2;
int_struct_pt1 = func(10);
int_struct_pt2 = func(16);
//int_struct.c
static int_struct int_struct_app;
int_struct * func(int a ){
int_struct_st.a = a;
int_struct_st.b = 15;
return &int_struct_st;
}
Thanks
Tried creating different variables . Debugged and saw the pointers had the same memory address.
My expectation is to get the best method in C to perform this function without being overwritten
2
Answers
Has only one instance and if you call your function it will always return the same address of the same object.
You need to create the struct every time this function is called:
Generally (as it is a small MCU medical project), you should implement statically allocated memory pools allocator/deallocator which will not fragment the heap. This is a very trivial example of the simplest implementation:
or with malloc
You can change
func
to be an initialization function:Elsewhere, define a variable for each instance:
If you really must use pointer variables:
Call the function to initialize the
int_struct
:or: