Being bored, I decided to take a look at the next logical link in the chain: how classes in C++ are represented in memory. Here's what came out:
- Code: Select all
libra% cat classTest.cpp
#include <stdio.h>
using namespace std;
/*******************************************
** Class SomeClass **
** Description: **
** A simple class that has 3 fields: **
** 1. integer array (5 ints) **
** 2. single integer **
** 3. single character **
** Constructor initalizes all fields **
*******************************************/
class SomeClass {
public:
SomeClass();
int a[5];
int b;
char c;
};
// Constructor for SomeClass
SomeClass::SomeClass() {
a[0] = 1;
a[1] = 4;
a[2] = 16;
a[3] = 64;
a[4] = 0x00ff00ff;
b = 42;
c = 'q';
}
int main() {
int sizeOfSomeClass = sizeof(SomeClass);// # of bytes in memory an
// instance of SomeClass takes
SomeClass * SC = new SomeClass(); // Create a new instance of
// SomeClass and point to it
// with SC
// info on SC
printf( "Size of SomeClass SC in memory: %i bytes.\n", sizeOfSomeClass);
printf( "Location of class in memory: %x \n\n", (int)SC);
// Printing memory contents for the SomeClass instance.
// This loop prints out the memory location and contents for each byte
// that the class takes up.
for (int i = 0; i < sizeOfSomeClass; i++) {
char memContent = *((char*)SC + i);
int value = (int)memContent;
value = value & 0x0ff;
printf ("Address 0x%x : 0x%x \n", ((int)SC + i), value);
}
return 0;
}
libra% g++ classTest.cpp -o classTest.exe
libra% chmod 550 classTest.exe
libra% classTest.exe
Size of SomeClass SC in memory: 28 bytes.
Location of class in memory: 27680
Address 0x27680 : 0x0
Address 0x27681 : 0x0
Address 0x27682 : 0x0
Address 0x27683 : 0x1
Address 0x27684 : 0x0
Address 0x27685 : 0x0
Address 0x27686 : 0x0
Address 0x27687 : 0x4
Address 0x27688 : 0x0
Address 0x27689 : 0x0
Address 0x2768a : 0x0
Address 0x2768b : 0x10
Address 0x2768c : 0x0
Address 0x2768d : 0x0
Address 0x2768e : 0x0
Address 0x2768f : 0x40
Address 0x27690 : 0x0
Address 0x27691 : 0xff
Address 0x27692 : 0x0
Address 0x27693 : 0xff
Address 0x27694 : 0x0
Address 0x27695 : 0x0
Address 0x27696 : 0x0
Address 0x27697 : 0x2a
Address 0x27698 : 0x71
Address 0x27699 : 0x0
Address 0x2769a : 0x0
Address 0x2769b : 0x0
libra%
Nothing too surprising... until the end. Everything looks cool up until the last 3 bytes, which are simply 0s.
Why is this? Now, if I change "char c" into "char c[4]" and init the char-sting to "qabc" (no null char, just for simplicity), the memory looks something like this:
Address 0x27698 : 0x71
Address 0x27699 : 0x61
Address 0x2769a : 0x62
Address 0x2769b : 0x63
[end of class]
That makes perfect sense; the size of each char is one byte here. But why add in the trailing 0s in the class data when there's only one character? Does this have some deep significance inside the computer, or is it my compiler just trying to keep all the data in memory aligned in a particular way?