C stack allocation size

I am trying to answer a quiz regarding the following code:

struct B {
  int _arr[5];
};
struct A{
  struct B* _b;
};

#include <stdlib.h>
int main(){
   struct A arr[5];
   struct A * a = (struct A*)malloc(sizeof (struct A));
   return 0;
}

I am trying to understand how much memory (in bytes) is allocated on the program's stack.

So I first used the following (and probably wrong) logic:

  • Calculated size of struct B = sizeof(int) * 5 = 20;
  • Calculated size of struct A = sizeof(B) = 20
  • I know that 2 is actualy wrong, because when I printed sizeof(B) I got a surprising 8. I really don't understandy why.

    Anyway, to understand how much memory was allocated on the stack:

  • The size of arr according to my logic is 20 * 5 = 100;
  • About *a, I don't really know. printing sizeof(a) shows 8, but again I don't understand why.
  • The sum of that is 108
  • BUT the actual answer is 24 :/ What am I missing?

    Thanks!


    As others have mentioned, there isn't really a correct answer. It's a terrible question, and in order to answer it you have to assume things which are not defined by C.

    That's probably not very helpful, though. Since you know the "correct" answer, it's possbile to figure out how they arrived at it:

    If you assume 32-bit pointers, sizeof(struct A) == 4 since struct A 's only field is a pointer to a struct B . So arr is 4 * 5 = 20 bytes, then add another 4 bytes for the a variable (which is another pointer).

    All the talk of sizeof(int) in the comments above is pointless; there are no int s on the stack. Or the heap, for that matter; you never actually allocate any struct B s.

    链接地址: http://www.djcxy.com/p/80214.html

    上一篇: .net框架中值类型和引用类型的内存分配

    下一篇: C堆栈分配大小