Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler (G++) seems to allocate more memory for instances of classes than it needs

I am learning about how compilers represent C++ programs in assembly. I have a question about something that the compiler does that I can't make sense of. Here is some C++ code:

class Class1 {
public:
  int i;
  char ch;
};

int main() {
  Class1 cls;
}

Compiling with "g++ -S " outputs this (I've stripped out everything but the function definition):

main:
    push    ebp
    mov     ebp, esp
    sub     esp, 16
    mov     eax, 0
    leave
    ret

I don't understand the line sub esp, 16. Why would it allocate 16 bytes for an instance of this class that only requires 8 when you take into account data structure alignment and padding?

It should be

[int i - 4 bytes][char ch - 1 byte][padding - 3 bytes]

should it not?

When I compiled the code with the class definition also including a double, i.e.

class Class1 {
public:
  int i;
  char ch;
  double dub;
}; 

it still allocated 16 bytes, which made sense in that case.

So why does the compiler allocate 16 bytes when it only needs 8?

like image 262
Grady S Avatar asked Nov 04 '11 03:11

Grady S


People also ask

Why does compiler use more memory?

Compilers generate intermediate object code which further requires linking, and hence require more memory. Continues translating the program until the first error is met, in which case it stops. Hence debugging is easy. It generates the error message only after scanning the whole program.

Does compiler allocate memory?

When a variable is declared compiler automatically allocates memory for it. This is known as compile time memory allocation or static memory allocation. Memory can be allocated for data variables after the program begins execution. This mechanism is known as runtime memory allocation or dynamic memory allocation.

How much memory is allocated for a class?

How much memory will be allocated for an object of class given below? Explanation: The size of an object of the class given in question will be of size 22 bytes.

Do classes allocate memory?

Memory allocation is the process of setting aside sections of memory in a program to be used to store variables, and instances of structures and classes. There are two basic types of memory allocation: When you declare a variable or an instance of a structure or class.


1 Answers

This has to do with stack-frame alignment, not structure alignment.

If you did a sizeof() on your objects, you'll see what you expect with struct alignment and padding.

However, stack-frames are slightly different. On most systems today, the stack alignment is 16 bytes (or more) to accommodate SSE memory accesses.

like image 112
Mysticial Avatar answered Oct 22 '22 20:10

Mysticial