1
 int a[2];

This in memory actually looks like:

 //Assuming int is 2 bytes 

 add=2000, a[0]=124    

 add=2002, a[1]=534 

How does this actually look like in memory

 struct l {

 struct l    * n;

 long int pad[7];

 };          

 struct l container;

I am unable to visualize. Please help!

BTW this is taken from section 3.3.2 of What Every Programmer Should Know About Memory

gpuguy
  • 4,607
  • 17
  • 67
  • 125
  • 2
    That's a type, not a variable; it won't be in memory. – Jonathan Leffler Jun 15 '12 at 17:08
  • 3
    *"//Assuming int is 2 bytes"* Not a great assumption these days, but ok. Also, that is not how the array would look in memory. It has been allocated as an array with two elements, yet you show three. – Ed S. Jun 15 '12 at 17:09
  • @EdS. My understanding was: what I see (and even what I dont see) on screen is stored in 'some' memory... so when I write this type, why no memory will be allocated? – gpuguy Jun 15 '12 at 17:17
  • No memory is allocated until you instantiate a variable of that type. The type definition really has meaning only to the compiler. – Dave Rager Jun 15 '12 at 17:20
  • @EdS. Sorry, I missed that line...updated. – gpuguy Jun 15 '12 at 17:37

3 Answers3

3

The layout of struct l would be as follows. As the book says it will occupy 32 bytes.

   addr   ref
   -----------------
   2000:  n
   2004:  pad[0]
   2008:  pad[1]
     ...
   2028:  pad[6]

On a 32-bit system struct l*, a pointer to a structure would occupy 4 bytes. A variable of type long int would occupy the same amount of memory.

Dima Chubarov
  • 16,199
  • 6
  • 40
  • 76
  • +1, but you forgot to mention that you're following the assumption that a `long int` is 4 bytes, as well as the pointer :) – Eitan T Jun 15 '12 at 17:15
  • @EitanT Thank you. This assumption is also taken in the Ulrich Drepper's paper. – Dima Chubarov Jun 15 '12 at 17:17
  • The OP said he assumes `int` is 16-bit so the system is likely a 8 or 16-bit system but not a 32-bit system. – ouah Jun 15 '12 at 17:29
1

Assuming a pointer in your architecture is 4 bytes and a long int in your architecture is 4 bytes:

struct l {
   struct l    * n;
   long int pad[7];
};

struct l someName;

layout will look like:

add=2000, someName.n
add=2004, someName.pad[0]
add=2008, someName.pad[1]
...
add=2028, someName.pad[6]
Dave Rager
  • 8,002
  • 3
  • 33
  • 52
1

this just means every time you allocate memory for struct l, you will need 4 byte (pointer) + 4 byte (let's say long int is 4 byte) * 7.

so using your system, it should be: add=2000 *n add=2004 pad[0] add=2008 pad[1] ...

Anthony Choi
  • 106
  • 4