Understating Persistence of Variables

Viewed 55

I am having trouble understanding why a variable is persisting. My understanding is that a local variable created in a function will no longer exist/hold value once the function exits. Ie it is popped off of the stack. The caveat to this being static or malloc'd variables.

I have an array of data static struct can_id_info can_id_info[MAX_CAN_ID_MAP_ENTRIES];. This data cannot be modified by a user. The user does need access to this data so I created two versions of the function.

Original:

struct can_id_info dbcppp_map_get(uint32_t can_id) {
    uint16_t i;
    static struct can_id_info temp;
    (void)memset(&temp, 0, sizeof(struct can_id_info));
    for(i=0; i<MAX_CAN_ID_MAP_ENTRIES; i++){
        if(can_id_info[i].can_id == can_id) {
            temp = can_id_info[i];
            break;
        }
    }
    return temp;
}

My initial thought was that because temp is static its memory will persist when the function exits. I then realized this assignment would allow a user to edit the data held within the array. Testing this I now see that the returned value cannot be used to update the original value.

New:

struct can_id_info dbcppp_map_get(uint32_t can_id) {
    uint16_t i;
    static struct can_id_info temp;
    (void)memset(&temp, 0, sizeof(struct can_id_info));
    for(i=0; i<MAX_CAN_ID_MAP_ENTRIES; i++){
        if(can_id_info[i].can_id == can_id) {
            memcpy(&temp, &can_id_info[i], sizeof(can_id_info[i]));
            break;
        }
    }
    return temp;
}

Now I have edited my function to return a copy of the data rather than a temp variable pointing to the data. Now here is where I am confused. Whether I make temp static or not the data persists when the function exits.

Can someone clarify? How is data meant to persist when a function exits?

0 Answers
Related