VolT
VolT

Reputation: 17

Indirect Addressing of Function Variables

Hi,

I have a function Temp_Picture. Function Temp_Picture has variable declarations as follows:

void Temp_Picture(void) 
{   
    unsigned char Year_T  = count_tens(Year);
    unsigned char Year_U  = count_ones(Year,Year_T);            
    unsigned char Day_T   = count_tens(Day);
    unsigned char Day_U   = count_ones(Day,Day_T);
    unsigned char Hours_T = count_tens(Hours);
    unsigned char Hours_U = count_ones(Hours,Hours_T);
    unsigned char Month_T = count_tens(Month);
    unsigned char Month_U = count_ones(Month,Month_T);
    unsigned char Minute_T= count_tens(Minute);
    unsigned char Minute_U= count_ones(Minute,Minute_T);
    function_b(Non void);

}

I want function_b to indirectly access the variables in Temp_Picture.

Since the variables are being created into the stack each time this function is called the variables addresses are effectively unknown however there is a pattern:

xxx

All of the variables are stacked together, and I want to take advantage of this situation, but I am not sure if this will work in all scenarios.

Do you think there is a problem with this and if so what is the best approach

Upvotes: 1

Views: 123

Answers (2)

MBlanc
MBlanc

Reputation: 1783

There may be a pattern. However, you shouldn't rely on this.

The C standard does not specify how the stack is arranged. Code that makes assumptions about the stack is very brittle. Changing compiler, or adding flags that may affect the stack (e.g., -O3) will break stuff.

Packing all related fields into a struct is the way to go:

struct {
    unsigned char Year_T;
    unsigned char Year_U;
    unsigned char Day_T;
    unsigned char Day_U;
    unsigned char Hours_T;
    unsigned char Hours_U;
    unsigned char Month_T;
    unsigned char Month_U;
    unsigned char Minute_T;
    unsigned char Minute_U;
} some_struct;

Then you just have to pass a reference to the struct:

function_b(&your_struct);

It's important to note that your_struct will only exist until Temp_Picture returns.

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234865

This will not work since you cannot guarantee that the variables are added to the stack in contiguous memory. (You can only guarantee that for elements of array types).

In fact to assume this is undefined behaviour.

Using an array unsigned char[] guarantees contiguity in memory so your function is then well-defined.

Upvotes: 2

Related Questions