Page 1 of 1

Odd issue with passing pointer to struct

Posted: Sun Apr 04, 2021 8:34 pm
by tomfrance
Hello team,

one part of the program looks like the following simplified excerpt:

Code: Select all

typedef struct A  {
    int valA;
    char strA[10];
} A;

typedef struct B  {
    int valB;
    char strB[10];
} B;

typedef struct col {
    A* structA;
    B* structB;
} col;


void app_main(void) {
    A structA;
    B structB;
    
    col mycol = {
        .structA = &structA,
        .structB = &structB,
    };
    
    printf("Address: %p\n", &mycol); // prints 0x3ffbaf10
    printf("Address: %p\n", mycol.A); //prints 0x3ffb60d8
    
    ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, ESP_EVENT_ANY_ID, &ip_event_handler, &mycol));
    

}

When I check the pointer addresses of mycol within ip_event_handler(), the address of mycol is the correct one (0x3ffb60d8) but

//within the event handler
printf("Address in ip_event_handler: %p\n", mycol->A);

prints 0x8008c8f0 instead of the expected 0x3ffb60d8, causing further memory access to fail. Do you have any idea, what is happening here or what I might do wrong? The 0x800... address seems pretty weird to me...

Maybe some background on what I am trying to accomplish: I need to pass several parameters to the event_handler, so I am combining them in a struct to realize this.

Thanks for you help!

Tom

Re: Odd issue with passing pointer to struct

Posted: Sun Apr 04, 2021 9:04 pm
by chegewara

Code: Select all

void app_main(void) {
    static A structA;
    static B structB;
    
    static col mycol = {
        .structA = &structA,
        .structB = &structB,
    };
OR

Code: Select all

col mycol = {};
void app_main(void) {
    static A structA;
    static B structB;
    
    mycol.structA = &structA;
    mycol..structB = &structB;

Re: Odd issue with passing pointer to struct

Posted: Mon Apr 05, 2021 9:55 am
by tomfrance
Hi chegewara!

Thanks a lot! This solved my problem indeed? Would you mind to elaborate what the reason is? Obviously, we are changing the scope of the variables, but why does this matter in this context?

Best, Tom

Re: Odd issue with passing pointer to struct

Posted: Mon Apr 05, 2021 10:42 am
by chegewara
It is a matter of scope, but since you want to pass it as pointer its no so important. More important is lifetime.
Local variables are created in task stack and valid only in function, then pointer in task stack is moved and memory used by that variable is reused in another function or just no longer valid.
"static" keyword (used on local variable) changes where variable is allocated in memory. As it is not allocated in task stack, but in regular heap it is not destroyed automatically on exit from function.

https://stackoverflow.com/questions/503 ... ction-in-c

Re: Odd issue with passing pointer to struct

Posted: Mon Apr 05, 2021 4:25 pm
by tomfrance
Thank you very much! Highly appreciated!