-3

My c++ code

#include <iostream>
using namespace std ;

struct Node {
    int data ;
    struct Node *next;
};

int main(){
    struct Node *head = NULL;
    struct Node *second = NULL;
    cout << sizeof(struct Node);
}

output to terminal

16

How is the size 16 ? Size of int is 4bytes. How come it's multiplied by 4 ? Please can anyone give detailed calculation ? Thanks !

Vivek Iyer
  • 154
  • 1
  • 6
  • 16

2 Answers2

2

An int is indeed 4 bytes (at least in x86 64 bit machines). A pointer (at least in x86 64 bit machines) is 8 bytes, so in theory the struct could have been 12 bytes. However, it's padded to a multiplication of the native word size (8 bytes) - and the closet round-up of 12 bytes would be 16 bytes.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • A similar, and easily testable alternative, the OP may be using a platform that uses 64 bit pointer and mandates them (pointers) reside on 8-byte boundaries. Assuming `int` is indeed four bytes on the platform, that four-bytes would then followed by 4 bytes of padding, then the 8-byte pointer. Some creative address-of using the members of an instance of the structure would be helpful in testing any of these hypothesis. – WhozCraig Jul 30 '17 at 06:52
  • 2
    Your description is misleading, there is most likely no padding at the end of the struct (but some in the middle). "padding to native word size" isn't a requirement on x86 64. – Mat Jul 30 '17 at 06:53
  • What is padding actually ? – Vivek Iyer Jul 30 '17 at 06:57
1

Structures are packed to the size of "biggest word" used. Eg, if you have such structure:

struct   ThreeBytes {
     char  one;
     short two;
};

Its size will be 4 bytes, because field one will be padded to the size of short, i.e. there is unused byte after that filed. If two would be an int, the structure will have size of two ints. This happens if you align your structure to that:

// this structure got size of 4 bytes.
struct   ThreeBytes {
     char  one;
     char  two;
     short three;
};

And this is unaligned one:

// This structure will have size 6 
struct   ThreeBytes {
     char  one;
     short two;
     char  three;
};

This is default behavior, there are compiler directives that allow change packing (see #pragma pack, for example, compiler means may be different). Essentially you can set the unit to which fields will be padded or disable padding by setting it to 1. But some platforms do not allow that at all.

Swift - Friday Pie
  • 12,777
  • 2
  • 19
  • 42
  • 1
    The name ThreeBytes is somewhat unfortunate for the last two structs, but otherwise some good examples. – Jonas Jul 30 '17 at 07:11
  • @Jonas it was intentional pun, it also misleading in first case, because that struct is four bytes, er, chars long. Some platforms have flexible definition of byte (that is minimal addressable unit _currently_) , which prompted this behavior. – Swift - Friday Pie Jul 30 '17 at 07:13