简体   繁体   中英

Memory is being shared in C++?

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 pstruct and pstruct2 point to the same location in memory (Since you assigned the address stored in ptr to both) and thus the data inserted by the MyStruct::store method was overwritten by the MyStruct2::store method.

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.

Undefined behaviour, which happens to successfully pretend it works.

3.10 Lvalues and rvalues [basic.lval]

...

10 If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:

— the dynamic type of the object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM