返回指针值在从方法中脱颖而出后会更改

Return pointer value changes after passing out from a method

本文关键字:脱颖而出 方法 指针 返回      更新时间:2023-10-16

我使用Eigen库中的代码有一个奇怪的行为。

如果我将指针分配给DoubleListCg->doubles,则我获得的DoubleListCg->doubles[i]的值是错误的。但是,如果我一一分配元素,那么我对上述指针数组的值是正确的。为什么?

这是我下面的代码:

#define DllExport   __declspec( dllexport ) 
#include "stdafx.h"
#define EIGEN_USE_MKL_ALL
#include <iostream>
#include "Eigen/Dense"
#include "Eigen/src/Core/util/MKL_support.h"
#include <Eigen/Sparse>
#include <Eigen/Eigenvalues>
#include <vector>
#include <Eigen/PardisoSupport>
using namespace std;
using namespace Eigen;
extern "C" struct DllExport DoubleListCg
{
    int num_points;
    double* doubles;
};
// working
void DoubleList(VectorXd vector, DoubleListCg *dListPtr)
{
    dListPtr->num_points = vector.size();
   dListPtr->doubles= (double*) malloc ( dListPtr->num_points*sizeof(double));
   for (int i = 0; i < vector.size(); i++)
   {
       dListPtr->doubles[i]=vector[i];
   }     
}
//not working
void DoubleList2(VectorXd vector, DoubleListCg *dList)
{
    dList->num_points = vector.size();
    dList->doubles =vector.data();
}
void VectorConvert()
{
    VectorXd vector(3);
    vector<<1,2,3;
    DoubleListCg dList;
    DoubleList(vector, &dList);  //this works; the dList gets the right values at first element
    DoubleListCg dList2;
    DoubleList2(vector, &dList2)  //this doesn't work; the dList2 gets the wrong values at first element

}

我挂断的一定是真正的基础。

相关问题:我是否可以将dList->doubles指向vector.data()?我不想一遍又一遍地复制所有内容

//not working
void DoubleList2(VectorXd vector, DoubleListCg *dList)
{
    dList->num_points = vector.size();
    dList->doubles =vector.data();
}

在上述函数中 vector是局部变量函数 DoubleList2。当功能返回或完成时,该局部变量将被破坏,dList->doubles成为一个悬空的指针,如果访问了这种悬空的指针,则会导致不确定的行为。

正确的实现将是:

void DoubleList2(VectorXd vector, DoubleListCg *dList)
{
    dList->num_points = vector.size();
    dList->doubles = (double*) malloc ( dList->num_points*sizeof(double));
    memcpy(dList->doubles, vector.data(), dList->num_points*sizeof(double));
}

void DoubleList(VectorXd vector, DoubleListCg *dListPtr) vector中是参数的(临时)副本。当您分配内存然后将值复制到其中时,它们将保留在dListPtr中。在无工作的情况下,.data()指针指向暂时分配的数组。当它不在范围内时,不能保证保证保留记忆。如果您通过引用传递vector,则内存将保持分配,直到原始内容不超出范围。