koldewb koldewb - 2 months ago 9
C Question

Memory allocation of functions and variables in C

Depended of the version of the C compiler and compiler flags it is possible to initialize variables on any place in your functions (As far as I am aware).

I'm used to put it all the variables at the top of the function, but the discussion started about the memory use of the variables if defined in any other place in the function.

Below I have written 2 short examples, and I wondered if anyone could explain me (or verify) how the memory gets allocated.

Example 1: Variable y is defined after a possible return statement, there is a possibility this variable won't be used for that reason, as far as I'm aware this doesn't matter and the code (memory allocation) would be the same if the variable was placed at the top of the function. Is this correct?

Example 2: Variable x is initialized in a loop, meaning that the scope of this variable is only within this loop, but what about the memory use of this variable? Would it be any different if placed on the top of the functions? Or just initialized on the stack at the function call?

Edit: To conclude a main question:
Does reducing the scope of the variable or change the location of the first use (so anywhere else instead of top) have any effects on the memory use?

Code example 1

static void Function(void){
uint8_t x = 0;

//code changing x
if(x == 2)
{
return;
}

uint8_t y = 0;
//more code changing y
}


Code example 2

static void LoopFunction(void){
uint8_t i = 0;

for(i =0; i < 100; i ++)
{
uint8_t x = i;
// do some calculations
uartTxLine("%d", x);
}

//more code
}

Answer

I'm used to put it all the variables at the top of the function

This used to be required in the older versions of C, but modern compilers dropped that requirement. As long as they know the type of the variable at the point of its first use, the compilers have all the information they need.

I wondered if anyone could explain me how the memory gets allocated.

The compiler decides how to allocate memory in the automatic storage area. Implementations are not limited to the approach that gives each variable you declare a separate location. They are allowed to reuse locations of variables that go out of scope, and also of variables no longer used after a certain point.

In your first example, variable y is allowed to use the space formerly occupied by variable x, because the first point of use of y is after the last point of use of x.

In your second example the space used for x inside the loop can be reused for other variables that you may declare in the // more code area.