gpt4 book ai didi

c - 使用 free() 会产生段错误

转载 作者:太空宇宙 更新时间:2023-11-03 23:53:39 26 4
gpt4 key购买 nike

我遇到了一个似乎无法通过内存分配解决的问题。

我使用 malloc 创建了 3 个动态分配的数组 (ipiv、k、b),但是当我尝试释放它们时,出现段错误。如果我不释放它们,代码可以正常工作(但如果我运行太多迭代,我就会耗尽内存)。

这是代码...我已经删除了所有不使用 3 个数组的部分,因为代码很长。

#include<stdio.h>
#include <string.h>
#include<stdlib.h>
#include<math.h>
#include <mpi.h>
#include "mkl.h"

#define K(i,j) k[(i)+(j)*(n)]

void dgesv_( const MKL_INT* n, const MKL_INT* nrhs, double* a,
const MKL_INT* lda, MKL_INT* ipiv, double* b,
const MKL_INT* ldb, MKL_INT* info );

int main()
{
int *ipiv=malloc(n*sizeof(int));
for (i=0; i<n; i++) {
ipiv[i]=0;
}

for (globloop=0; globloop<=lasti; globloop++) {

double a[ndofs];
double rhs[ndofs];
double F[ndofs];

double *k=malloc(n*n*sizeof(double));


//var for stiffness matrix (this is the one acutally fed to dgesv)
//see define at top
for (i=0; i<n; i++) {
for (j=0; j<n; j++) {
K(i,j)=0.0;
}
}

//bunch of stuff modified, a,rhs,and F filled... ect

while (sos>=ep && nonlinloop<=maxit) {

double KFull[ndofs][ndofs];
for (i=0; i<ndofs; i++) {
for (j=0; j<ndofs; j++) {
KFull[i][j]=0.0;
}
}

//KFull filled with values..

//trim the arrays to account for bcs
double *b=malloc(n*sizeof(double));
for (i=0; i<n; i++) {
b[i]=rhs[i+2];
}

//k array filled
//see define above
for (i=0; i<n; i++) {
for (j=0; j<ndofs-2; j++) {
K(i,j)=KFull[i+2][j+2];
}
}

//SOLVER
dgesv_(&n,&one,k,&n,ipiv,b,&n,&info);

//now we must take our solution in b, and place back into rhs
for (i=0; i<n; i++) {
rhs[i+2]=b[i];
}
nonlinloop++;
free(b);
}
free(k);
}
free(ipiv);
return 0;
}

释放这 3 个变量中的任何一个都会给我一个段错误。我对此非常困惑。

最佳答案

如果 n=ndofs-4(如 OP 评论中所述),则 ndofs-2 大于 n。然后代码将破坏内存

K(i,j)=KFull[i+2][j+2];

因为 j 运行到 ndofs-2-1 并且 K 被(仅)定义为 K[0。 .n-1][0..n-1].

关于c - 使用 free() 会产生段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13631747/

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