Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with local variable ordering [duplicate]

I have been noticing that some of the programs that I write in C have not been working on my machine, but they works other others. So to test this, I wrote a simple program to test how the stack is pushing and popping local variables:

#include <stdio.h>
#include <string.h>

int main() {
    char char_test[10];
    int int_test = 0;

    strcpy(char_test, "Hello");
}

I then debugged this program and found that int_test had a higher memory address than char_test, even though, according to my knowledge, the first declared local variable is supposed to have a higher memory address. I then added two print functions that printed the memory addresses of the variables:

#include <stdio.h>
#include <string.h>

int main() {
    char char_test[10];
    int int_test = 0;

    strcpy(char_test, "Hello");

    printf("Address of char_test: 0x%x\n", &char_test);
    printf("Address of int_test: 0x%x\n", &int_test);
}

Now, the first local variable has a higher memory address than the second. Does printing the addresses change the ordering of the variables? Am I doing something wrong?

like image 755
nope122 Avatar asked Mar 03 '26 08:03

nope122


1 Answers

Sequential requirement to which you are referring is for members of structs. There is no requirement for a compiler to order local variables one way or the other. In fact, there is no a requirement for a compiler to use stack for its automatic variables, or even to allocate them at all, if it could get away with it.

In your example, it looks like the compiler did just that: since int_test is not used, the compiler pretended that it does not exist. Once you started using it by taking its address, the compiler was forced to allocate it. It happened to allocate the variable ahead of char_test, but it is not under an obligation to do so.

like image 117
Sergey Kalinichenko Avatar answered Mar 05 '26 08:03

Sergey Kalinichenko