I'm having an issue that I cannot seem to fix with my memory allocations.
I create 3 dynamically allocated arrays (ipiv,k,b) using malloc, but when I try and free them, I get a seg fault. If I don't free them, the code works fine (but if I run too many iterations, I run out of memory).
Here is the code... I've taken out all of the parts that do not use the 3 arrays, since the code is pretty long.
#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;
}
Freeing any one of these 3 variables gives me a segmentation fault. I am super-confused about this.
ndofs-2
is greater thann
? - Sergey Kalinichenkodgesv_
doesn't already free them? Callingfree
on a pointer that has already been freed is normally aSIGSEGV
. - Sergey L.