0

I am using ARM (32-bit). Assume the following function uses a stack frame to store the variables locally.

void func() {
   char ch;     //0x8? Shouldn't this be 0x4 with padding?
   int a, b, c; //each are 0x4
   double m, n; //each are 0x8
}

The size of all of these local variables is 0x24. When I subtract the three ints (0xC) and the two doubles (0x10), I am left with 0x8, meaning that the char is taking up 8 bytes. I understand that padding helps with alignment, but if char is of size 1 and it was supposed to align, wouldn't it pad to 0x4?

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
w0f
  • 908
  • 9
  • 23
  • 1
    Padding. Google it. – Bathsheba May 03 '17 at 19:20
  • I'm not understanding why it pads to 8 instead of 4 though – w0f May 03 '17 at 19:20
  • 1
    How did you determine this? – harold May 03 '17 at 19:24
  • How do you determine that the size of these variables are 0x24 ? doubles might need 8 byte alignment and a stack frame might need more space than just the sum of its local variables ,e.g. to store saved registers, return address and so on. – nos May 03 '17 at 19:28
  • 1
    It's a quiz from my architecture class. The question states that sp is 0x7810 when the function is called and sp is 0x77e8 when it is initalized, making the frame size 0x28. Since fp is popped to the stack, we can subtract 0x4 from that value to get 0x24. From there, I know that ints are 0x4 and doubles are 0x8, so subtracting those leaves 0x8 for just the char. – w0f May 03 '17 at 19:30
  • Or it's just for alignment – harold May 03 '17 at 19:31
  • 2
    There is no stack in the C language. On ARM, none of the variables exist on the stack, but are stored in registers, unless you take their address. More: if you enable optimisation, they don't even exist, because you don't use them. Provide a [mcve] and a clear problem description. – too honest for this site May 03 '17 at 19:34
  • ... and even if they exist on the stack, any compiler would probably rearrange for a better stack layout (=first 8 byte-aligned double, then 4-byte aligned ints, finally the `char`, then 3 bytes of padding to keep the stack aligned). – Matteo Italia May 03 '17 at 19:48
  • This is a great read. http://www.catb.org/esr/structure-packing/ – jiveturkey May 03 '17 at 19:49
  • struct member alignment is something you can configure in your compiler. Some default to 8 byte alignment. – Justin J. May 03 '17 at 19:49
  • This is really an ARM assembly question, rather than a C question. The stack frame includes more than just your local variables. It also includes space for any unnamed temporary variables the compiler needs, space to save values from registers if the calling convention requires it, and space to record the return address. To answer this question fully, we need a more complete example (including disassembly) and we need to know what operating system you're using. – pburka May 03 '17 at 20:24

0 Answers0