构造函数似乎正确分配了指针,但指针在构造函数外部发生了变化

Constructor seemed to have assigned pointer correctly, but pointer changes outside constructor

提问人:Metersquared 提问时间:10/4/2023 更新时间:10/4/2023 访问量:12

问:

我目前有一个类,它有一个构造函数,它基于将一些值从 npz 导入到双指针 A。

StateSystem::StateSystem(std::string filename)
{
    cnpy::NpyArray A_npy = cnpy::npz_load(filename, "A");
    StateSystem::A = (double *)mkl_malloc(A_npy.shape[0] * A_npy.shape[1] * sizeof(double), 64);
    this->StateSystem::A = A_npy.data<double>();

    std::cout << "A (in constructor):" << std::endl;
    for (size_t i = 0; i < StateSystem::n; i++)
    {
        for (size_t j = 0; j < StateSystem::n; j++)
        {
            std::cout << " " << StateSystem::A[j + StateSystem::n * i] << " ";
        }
        std::cout << std::endl;
    }
}

由于这是对指针mkl_malloc的分配,因此我尽量小心并尝试进行一些检查,以确保导入的值正确。

我尝试使用npz,其中A包含Id,并且从构造函数中,最后几行正确打印:

A (in constructor):
1  0  0  0
0  1  0  0
0  0  1  0
0  0  0  1

但是,当我创建一个打印变量的类方法时,我的变量似乎发生了变化。

void StateSystem::info()
{
std::cout \<\< UNDERLINE \<\< "State system: n=" \<\< StateSystem::n \<\< " m=" \<\< StateSystem::m \<\< " p=" \<\< StateSystem::p \<\< CLOSEUNDERLINE \<\< std::endl;
std::cout \<\< "A:" \<\< std::endl;
for (size_t i = 0; i \< StateSystem::n; i++)
{
for (size_t j = 0; j \< StateSystem::n; j++)
{
std::cout \<\< " " \<\< StateSystem::A\[j + StateSystem::n \* i\] \<\< " ";
}
std::cout \<\< std::endl;
}

此功能导致:

State system: n=4 m=1 p=1
A:
1\.13825e-313  -1.74758e+260  0  0
0  1  0  0
0  0  1  0
0  0  0  1

知道为什么吗???

Pointers 构造函数 memory-leaks malloc intel-mkl

评论

0赞 ssbssa 10/5/2023
我认为只复制指向数据的指针,而不是内容,一旦你离开构造函数,你实际上从已经释放的指针读取。this->StateSystem::A = A_npy.data<double>();

答: 暂无答案