Can someone explain to me how data is being utilized since I was messing around with the following code…:
#include <stdio.h>
#include <stdlib.h>
typedef struct MyStruct {
public:
void print() {
printf("MyStruct.print():\n\ta: %i\n\tb: %i\n\n", a, b);
}
void store() {
a = 2;
b = 3;
}
private:
int a, b;
};
typedef struct MyStruct2 {
public:
void print() {
printf("MyStruct2.print():\na: %i\nb: %i\n\n", a, b);
}
void store() {
a = 1024;
b = 3077;
}
private:
int a, b;
};
int main() {
void *ptr = malloc(sizeof(MyStruct)); // sizeof(MyStruct) == sizeof(MyStruct2)
MyStruct* pstruct = (MyStruct*)ptr;
pstruct->store();
pstruct->print();
MyStruct2* pstruct2 = (MyStruct2*)ptr;
pstruct2->store();
pstruct->print();
return 0;
}
and I got the following results:
MyStruct.print():
a: 2
b: 3
MyStruct.print():
a: 1024
b: 3077
As you can see I didn’t allocate any more memory for the pstruct2, yet I was able to access it. Can anyone explain to me, or at least give me a reference/tutorial to something that is close to this that explains it.
Both
pstructandpstruct2point to the same location in memory (Since you assigned the address stored inptrto both) and thus the data inserted by theMyStruct::storemethod was overwritten by theMyStruct2::storemethod.In other words, this is happening because you are explicitly making it happen. If your two classes weren’t identical or if the compiler had produced different memory layouts of them, you would’ve possibly read out garbage data.
Basically, C++ allows you to write into any dynamically allocated memory as much as you want, happily ignorant and oblivious of the fact that you had previously used this memory for another object.