samedi 12 mars 2022

C++ Crash on x64

I have to do a little c++ reflection in my way, by creating a pointer for each property of my class(I have create a tool to help me generate corresponding c++ code), but surprise, Building on x86 mode worked fine, but on x64 mode it's crashed, I have no idea why! here is my code.

Product.h File

    class Product
    {
    public:
        int ID;
        std::string  Designation;
    };
  class Property
    {
    public:
        std::string Name;
        int Shift;
    };
    class ProductSchema
    {
    private: 
        ProductSchema();
    public: 
        static ProductSchema* Default();
        ProductSchema(const ProductSchema& other) = delete;
        Property ID;
        Property Designation;
        Property Prix;
    };

Product.cpp File

ProductSchema::ProductSchema()
{  
    Product* p = new Product(); 
    ID.Name = "ID";
    ID.Shift = (int)(int*)&p->ID - (int)p;    

    Designation.Name = "Designation";
    Designation.Shift = (int)(int*)&p->Designation - (int)p;
}
ProductSchema* ProductSchema::Default()
{
    static ProductSchema* instance_;
    if (instance_ == nullptr)
        instance_ = new ProductSchema;
    return instance_;
}

main.h file

 int main()
    {     
        for (int i = 0; i < 10000; i++)
        {
            Product* p = new Product();
            int* pID = (int*)((unsigned long int)p + ProductSchema::Default()->ID.Shift);
            *pID = i; // <--- error here 
        } 
    }




Aucun commentaire:

Enregistrer un commentaire