0

My address checking code is,

#include <stdio.h>


int main(){
        int num1, num2, *pNum1, *pNum2;

        num1 = 123;
        num2 = 321;

        pNum1 = &num1;
        pNum2 = &num2;

        printf("pNum1 = %p\n", pNum1);
        printf("pNum2 = %p\n", pNum2);

        pNum2++;

        printf("pNum2 = %p\n", pNum2);

        printf("*pNum2 = %i\n", *pNum2);



        return 0;

}

My output is,

enter image description here

I declared first num1 and second num2 and so on. variables keep according stack then num1 address should be higher than num2 but my output num2 is higher than num1. What is the reason?

please give an advise. Thank you.

kiner_shah
  • 3,939
  • 7
  • 23
  • 37
  • 5
    "*num1 address should be higher than num2*". That's an incorrect assumption. The compiler is free to arrange the variables as it likes. – kaylum Sep 12 '21 at 06:44
  • After `pNum2++` any attempt at accessing `*pNum2` invokes UB. It may crash your computer, it may do what you expect, it may print the lyrics of the national anthem of Spain, ... – pmg Sep 12 '21 at 06:51
  • @pmg but I print num1 and num2 addresses directly and same thing happened. –  Sep 12 '21 at 06:55
  • @kaylum you mean, does stack depend on the compiler? –  Sep 12 '21 at 06:57
  • 2
    The stack layout depends on the compiler, the optimization settings, the code in the function, the code in other functions (if inlining is done), and basically everything else you can think of. Compilers could even randomize it as a hardening measure against security exploits. Some C implementations may not use a stack at all. In short, you can't make any assumptions. If you're reading some book or article that says it is always arranged in a certain way, they are wrong (or they are talking about a very specific compiler). – Nate Eldredge Sep 12 '21 at 07:00
  • duplicates: [Order of local variable allocation on the stack](https://stackoverflow.com/q/1102049/995714), [Order of memory allocation in C](https://stackoverflow.com/q/58148075/995714) – phuclv Sep 12 '21 at 07:01
  • @pmg I just ran the code. It *did* print out the [official lyrics of the national anthem of Spain](https://worldpopulationreview.com/anthems/spain). – JeremyP Sep 12 '21 at 09:39
  • Congrats @JeremyP... you win the undetectable UB award xD – pmg Sep 12 '21 at 11:40

0 Answers0