Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcc preserves memory allocation after changing variable declaration order [duplicate]

Tags:

c

gcc

I have a function of this form:

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

When I debug the program I can see that the auth_flag variable is 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 variable auth_flag is still allocated after the password variable in the stack.

What I'm looking for is any way to avoid/control that, whether with a compilation option or in-code compiler directives.

like image 643
B. Kostas Avatar asked Oct 17 '16 07:10

B. Kostas


1 Answers

According to GCC documentation "Common Function Attributes":

  • no_reorder

Do not reorder functions or variables marked no_reorder against each other or top level assembler statements the executable. The actual order in the program will depend on the linker command line. Static variables marked like this are also not removed. This has a similar effect as the -fno-toplevel-reorder option, but only applies to the marked symbols.

And in "Optimize Options":

  • -fno-toplevel-reorder

Do not reorder top-level functions, variables, and asm statements. Output them in the same order that they appear in the input file. When this option is used, unreferenced static variables are not removed. This option is intended to support existing code that relies on a particular ordering. For new code, it is better to use attributes when possible.

like image 153
FloppySoftware Avatar answered Nov 15 '22 07:11

FloppySoftware