Gcc retains memory allocation after changing the declaration of a variable

I have a function of this form:

void authenticate() { int auth_flag; char password[16]; ... } 

When I debug the program, I see that the auth_flag variable is located after the password variable in the stack (which seems normal).

Now, when I change the order of variable declarations:

 void authenticate() { char password[16]; int auth_flag; ... } 

I see that the auth_flag variable is still allocated after the password variable in the stack.

What I'm looking for is any way to avoid / control this, whether with compilation options or inside the compiler.

+5
source share
2 answers

According to the GCC Documentation "General Function Attributes" :

  • no_reorder

Do not reorder functions or variables marked no_reorder against each other, or top-level assembly instructions of an executable file. The actual order in the program will depend on the linker command line. Static variables marked like this are also not deleted. This is similar to the -fno-toplevel-reorder , but applies only to marked characters.

And in "Optimize Settings" :

  • -fno-toplevel-reorder

Do not reorder top-level functions, variables, and asm statements. Print them in the same order as in the input file. When this parameter is used, static variables without references are not deleted. This parameter is intended to support existing code, which depends on the specific order. For new code, it is better to use attributes when possible.

+4
source

In truth, you program the compiler and then program the machine. The compiler will decide on your code. It will do things on the stack that can help with caching and thus can move things around. There will be compiler options to stop this. Indeed, you may need to use the volatile keyword to avoid deleting variables at all.

+1
source

Source: https://habr.com/ru/post/1258315/


All Articles