1

When compiling C code in GCC, is there any way to guarantee that the stack variables will appear in the stack in the order i declare them (or in reversed order, doesn't matter to me)? I know this is possible via structs but I would rather not use them.

leetrobot
  • 153
  • 1
  • 8
  • 5
    Why do you want this? And what's wrong with a `struct`? – Fred Foo Mar 02 '12 at 15:00
  • I want to demonstrate a certain stack overflow issue when buffers and pointers and positioned in a certain way. And I do not want to use structs (rather, I can't) because some of the variables are declared in inline functions which are later called from the main routine. – leetrobot Mar 02 '12 at 15:03
  • Also, I looked at "Can a C compiler rearrange stack variables?" and basically the whole thread was like "yea, this can happen, unless you use structs" which as I said is something I wish not to do. – leetrobot Mar 02 '12 at 15:04
  • 3
    Nothing has changed in this regard in the meantime – Gunther Piez Mar 02 '12 at 15:16
  • 1
    You can't even guarantee that your variables are stored on the stack --- the compiler may keep them entirely in registers. Or it may store two variables in the stack slot. This is all totally up to the compiler. – David Given Mar 02 '12 at 22:44

3 Answers3

4

The only way would be a struct which includes all variables in the order you like.

For local variables the compiler is free to reorder/reuse variables at any order it suits her. Some variables may not have a memory location at all, they live only in registers, others will be optimized away completely.

Gunther Piez
  • 29,760
  • 6
  • 71
  • 103
0

If you are adamant that you do not want to use a struct then you will have to allocate the stack memory yourself with alloca(). But then you will need to manage your local variables manually within that block of stack memory.

I would not recommend that you do this. Use a struct.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
0

The most reliable approach is to direct gcc to produce assembly language output using gcc -S, and examine the assembly language output to find out which variables have been put where. If you compile without optimisations, the variables probably won't get removed or rearranged, and if you assign different values to each local variable it should be easy to spot each one.

I admit that this is not very high-tech. But if you want to be sure that gcc is generating code that works in a particular way, you will have to look at the code it generates...