I cannot figure out what is going on with my code. I am developing on a STM32F7 board.
The fact is, I have typedef'd a struct of pointers:
typedef struct
{
Pos_2D_t *a;
Pos_2D_t *p;
Pos_2D_t *pp;
Pos_2D_t *af;
Pos_2D_t *pf;
Pos_2D_t *ppf;
}signal_t;
Declared a pointer to it:
signal_t *positions;
and wrote a init function to malloc the struct - here the content:
FILTER_Init(signal_t *signal){
signal = malloc(sizeof(signal_t));
if(signal != NULL)
{
signal->a = malloc(sizeof(Pos_2D_t));
signal->p = malloc(sizeof(Pos_2D_t));
signal->pp = malloc(sizeof(Pos_2D_t));
signal->af= malloc(sizeof(Pos_2D_t));
signal->pf = malloc(sizeof(Pos_2D_t));
signal->ppf = malloc(sizeof(Pos_2D_t));
}
}
And call it:
FILTER_Init(positions);
The problem is, when I try to copy a value inside of each Pos_2D_t element
positions->a->x = value;
positions->a->y = value;
I fall into Hard fault. From debugging with Keil uVision, I see that the value of the pointer to struct (its address) is 0x0000, but I see the other Pos_2D_t* elements having a meaningful address wrt the memory map of my board.
I cannot understand why I see a 0x0000 address for the struct, and correct addresses for the inner elements(it should not allocate the inner Pos_2D_t having a check on signal != NULL, right?). I am quite sure I am messing with memory allocation, but I cannot find where and why.
If I declare the struct not as a pointer, and I allocate only the inner elements of the struct, like that:
FILTER_Init(signal_t *signal){
signal->a = malloc(sizeof(Pos_2D_t));
signal->p = malloc(sizeof(Pos_2D_t));
signal->pp = malloc(sizeof(Pos_2D_t));
signal->af = malloc(sizeof(Pos_2D_t));
signal->pf = malloc(sizeof(Pos_2D_t));
signal->ppf = malloc(sizeof(Pos_2D_t));
}
It all goes well and my program does not crash or faults. Could you guys please help me?
EDIT
my Pos_2D_t struct is:
typedef struct
{
float x;
float y;
}Pos_2D_t;
EDIT 2 as someone already found out, my question has already been answered earlier. many thanks!