分配的内存int[8]为什么后面的内存还能读写


#include <iostream>
#include <exception>

using namespace std;

class test{
public:
    int *p;
    test(){
        this->p = new int[8];
    }
    ~test(){
        if (p != nullptr)
            delete [] this->p;
    }
};


int main(){
    test c;
    cout<<sizeof(c.p)<<endl;
    try {
        for (int i = 0; i < 100; i++){
            c.p[i] = i + 100;
        }
        for (int i = 0; i < 100; i++){
            cout<<c.p[i]<<" ";
        }
        cout<<endl;
    }catch(const char* msg){
        cerr << msg << endl;
    }
}

img

运气,因c/c++不是内存安全的语言,所以你可以这样
rust就不可以了,会严格检测内存边界