gpt4 book ai didi

c++ - 我处理这个的方式有内存问题吗?

转载 作者:行者123 更新时间:2023-11-28 02:55:27 24 4
gpt4 key购买 nike

我正在为 Eigen QR 编写一个包装器供我个人使用,我想知道我的实现中是否存在任何内存泄漏或未记录的行为,尤其是在函数 void get_QR(double* A, int m, int n , double*& Q, double*& R).答案如预期。这与我之前的问题有关 here .

using std::cout;
using std::endl;
using namespace Eigen;

/*!
Obtains the QR decomposition as A=QR, where all the matrices are in Eigen MatrixXd format.
*/
void get_QR(MatrixXd A, MatrixXd& Q, MatrixXd& R) {

int m = A.rows();
int n = A.cols();
int minmn = min(m,n);

// A_E = Q_E*R_E.
HouseholderQR<MatrixXd> qr(A);
Q = qr.householderQ()*(MatrixXd::Identity(m, minmn));
R = qr.matrixQR().block(0, 0, minmn, n).triangularView<Upper>();
}

/*!
Obtains the QR decomposition as A=QR, where all the matrices are in double format.
*/
void get_QR(double* A, int m, int n, double*& Q, double*& R) {
MatrixXd Q_E, R_E;
int minmn = min(m,n);

// Maps the double to MatrixXd.
Map<MatrixXd> A_E(A, m, n);

get_QR(A_E, Q_E, R_E);

Q = (double*)realloc(Q_E.data(), m*minmn*sizeof(double));
R = (double*)realloc(R_E.data(), minmn*n*sizeof(double));
}


int main(int argc, char* argv[]) {
srand(time(NULL));

int m = atoi(argv[1]);
int n = atoi(argv[2]);

// Check the double version.
int minmn = min(m,n);
double* A = (double*)malloc(m*n*sizeof(double));
double* Q = (double*)malloc(m*minmn*sizeof(double));
double* R = (double*)malloc(minmn*n*sizeof(double));

double RANDMAX = double(RAND_MAX);
// Initialize A as a random matrix.
for (int index=0; index<m*n; ++index) {
A[index] = rand()/RANDMAX;
}

get_QR(A, m, n, Q, R);
std::cout << Q[0] << std::endl;

// Check the MatrixXd version.
Map<MatrixXd> A_E(A, m, n);
MatrixXd Q_E, R_E;
get_QR(A_E, Q_E, R_E);

cout << Q[0] << endl;
cout << Q_E(0,0) << endl;

free(A);
free(Q);
free(R);
}

例如,我得到输出为

-0.360995
-0.360995
-0.360995

最佳答案

realloc不保证与 operator new[] 兼容和 operator delete[] , 只有 mallocfree .

我会替换掉你所有的 double*指针 std::vector<double>对象。

关于c++ - 我处理这个的方式有内存问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22116774/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com