Size of struct allocation

1

When I declare a normal variable of type int for example, the compiler goes there and, depending on the architecture, separates 4 bytes .

struct exemplo{
  int x;
  int b;
};

int main(){
   struct exemplo exemplo;
}

When I declare the variable exemplo in main the compiler allocates in the stack all that is in struct exemplo . The correct would not be in the variable exemplo to allocate the size of the struct , which in this case would not be 8 bytes ?

And in case of dynamic memory allocation, when allocating a type int it allocates 4 bytes of address, but when allocating a struct all variables of struct are allocated. Would not it just have to be the space of struct in the pointer?

    
asked by anonymous 12.04.2015 / 04:36

1 answer

3

The size of a structure's allocation is not that simple, there's the issue of alignment . Depending on the compiler, the directives, the code, and the platform you're running on may be different but there's a reasonable chance that it's 8 bytes anyway, just do not count this as being right. This can be found by code .

#include <iostream>
using namespace std;

struct Exemplo { int x; int b; };

int main() {
    Exemplo exemplo;
    cout << "Tamanho de exemplo: " << sizeof(exemplo) << endl;
    cout << "Valor de exemplo.x: " << exemplo.x << endl;
    cout << "Valor de exemplo.b: " << exemplo.b << endl;
    Exemplo *exemplo2 = new Exemplo;
    cout << "Tamanho de exemplo2: " << sizeof(exemplo2) << endl;
    cout << "Tamanho do objeto apontado por exemplo2: " << sizeof(*exemplo2) << endl;
    cout << "Valor de exemplo2 (o ponteiro): " << exemplo2 << endl;
    cout << "Valor de exemplo2->x: " << exemplo2->x << endl;
    cout << "Valor de exemplo2->b: " << exemplo2->b << endl;
    cout << "Tamanho de exemplo2.x: " << sizeof(exemplo2->x) << endl;
    return 0;
}

Dynamic allocation allocates the memory required for the object you want to allocate. It does not matter if it is in the stack or heap , the size should be the same. In case it will allocate space for an object, in its example it would have 8 bytes and the variable will receive the pointer for this object. The pointer size is fixed to the application, all pointers have the same size, which varies is the size of the object it points to. Pointer and the object he points out are distinct things that have an eventual relationship. In case the object that would be pointed out should have 8 bytes , after all it would be the same structure.

In a simple example the object would be in the heap and the pointer allocated in the variable would be in stack . But nothing prevents the pointer from being heap also just the code you prefer to put there for some reason.

If you want to understand more about pointer, you have a question on the subject here on the site.

    
12.04.2015 / 04:51