Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 286 Vote(s) - 3.51 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Compiler (G++) seems to allocate more memory for instances of classes than it needs

#1
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 <source>" 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][1]?

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?


[1]:

[To see links please register here]

"Wikipedia on data structure alignment"
Reply

#2
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.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through