2012-11-29 36 views
2

我有一個問題,我似乎無法解決我的內存分配問題。使用免費()創建分段錯誤

我使用malloc創建了3個動態分配的數組(ipiv,k,b),但是當我嘗試並釋放它們時,出現seg故障。如果我沒有釋放它們,代碼運行良好(但是如果我運行了太多迭代,則內存不足)。

這是代碼...我已經拿出所有不使用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個變量中的任何一個都會導致分段錯誤。我對此感到非常困惑。

+2

用valgrind運行它,它會告訴你什麼是錯的。 –

+2

'ndofs-2'是否可能大於'n'? – dasblinkenlight

+0

nope,它們被專門設置爲n = ndofs-4。 – user1864020

回答

1

如果n=ndofs-4(如OP的評論中提及),那麼ndofs-2是大於n。然後該代碼將在

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

j因爲運行被破壞存儲器高達ndofs-2-1K是(僅)定義爲K[0..n-1][0..n-1]