2011-07-27 3 views
0

디버그에서 코드를 실행할 때 다음과 같은 오류 메시지가 계속 나타납니다.손상된 힙 -C

Windows가 선형 방정식 331.exe에서 중단 점을 트리거했습니다.

선형 방정식 331.exe 또는로드 한 DLL에 버그가 있음을 나타 내기 때문에 힙이 손상되었을 수 있습니다.

그런 다음 중단/계속이 나타납니다.

코드는 Gauss-Siedel Iterative 메서드를 사용하여 nx 시스템의 선형 방정식을 해결합니다. 이 경우 3 개의 번지 코드에 3 개의 사람 (A, B, C)이 붙어있는 총 스트레치 (X)를 찾아야합니다. 각 솔루션은 사람들의 다른 순열을 가지고있다. (예 : A, B, C, A, C, B, B, A, C 등)

우리는 alloc.h라는 메모리 할당 헤더 파일을 제공 받았다. 내 문제를 일으킬 수있는 작동 방식을 완전히 이해하지 못했지만 더 많은 변수에 대해 ALLOCATE()를 사용하기 전에는 정상적으로 작동했습니다. 왜 이런 일이 일어나는지 설명하는 데 도움이 될 것입니다.

주요 코드가 첫 번째입니다. 헤더 파일은 맨 아래에 있습니다. 죄송합니다 코드가 좀 지저분한 경우. 내가 언급하려 최선을 내가 할 수있는 등 :

#define _CRT_SECURE_NO_DEPRECATE 
#define _CRT_SECURE_NO_WARNINGS 


#include <assert.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <math.h> 

#include "allocate.h" 
#include "iter.h" 

void position_solve(int n,int k,double X[], double x[],double order[]); 
void inverse(int n, double A[],double X[],double b[]); 
void swap(double *,double*); 
void permute(int n, double a[]); 
int noofpermutations(); 
void next(int n,double a[]); 
void permutation(int n, double a[]); 
int count = 0; 

int main(void) 
    { 
int i,j,k,num=0, n=3, p=noofpermutations(n); 
    double *A = NULL, *m = NULL, *X = NULL,* b= NULL,*K=NULL, *x=NULL, *order=NULL, *length=NULL; 

/* Allocate the required memory */ 
ALLOCATE(A, double, n * n); 
ALLOCATE(m, double, n * p); 
ALLOCATE(b, double, n); 
ALLOCATE(x, double, n * p); 
ALLOCATE(K, double, n * p); 
ALLOCATE(X, double, n); 
ALLOCATE(order,double, n); 
ALLOCATE(length,double,1); 


/*Defining the Order of A,B,C jumpers where 1 = A, 2 = B, 3 = C*/ 
printf("+-----------------------------------------------------------------------------+\n"); 
printf("The Order of Bungee Jumpers A,B and C is represented by \n1,2,and 3 respectively. \n"); 
printf("\n+-----------------------------------------------------------------------------+\n"); 

for(i=0;i<n;i++){ 
    order[i] = i+1; 
    b[i] = 0; 
} 

length[0] = 0; 
/*Hardcoding k(spring constant),x(initial length of each bungee cord) and m(mass in kg) for 3 bunjee jumpers*/ 
K[0] = 50; 
K[1] = 100; 
K[2] = 50; 

m[0] = -60*9.81; 
m[1] = -70*9.81; 
m[2] = -80*9.81; 

x[0] = 20; 
x[1] = 20; 
x[2] = 20; 

for(i=3;i<n*p;i++){ 
K[i] = 0; 
m[i] = 0; 
x[i] = 0; 
} 

/*Generate Permutations of K,m for the given Order of Bungee Jumpers */ 
permutation(n,K); 
permutation(n,m); 
permutation(n,order); 

/*Calculate A matrix*/ 
for(k=0;k<p;k++){ 
    for (i = 0; i < n; i++) { 
     for (j = 0; j < n; j++) { 
      if(i==j){ 
       A[i*n + j] = -K[k*n + i] - K[k*n + j]; 
      } 
      else if(j == (i+1)){ 
       A[i*n+j] = K[k*n + j]; 
       A[j*n+i] = K[k*n + j]; 
      } 
      else if(j>(i+1)){ 
       A[i*n + j] = 0; 
      } 
     } 
    } 

    printf("\nFor a Bungee Jumper order %1.0lf %1.0lf %1.0lf :\n",order[k*n],order[k*n+1],order[k*n+2]); 

    /*Determine multiple X (stretch of bungee in m) vecotrs*/ 
    /*Extract a single RHS vector (from B) into b*/ 
    for(i=0;i<n;i++){ 
     b[i]= m[k*n + i]; 
    } 
    /*Perform Iterative Method*/ 
    iter_solve(n, A, b, X); 

    /* Output X solutions*/ 
    printf("\nX = [\n"); 
    for (j = 0; j < n; j++) { 
      printf("%f ", X[j]); 
     printf("\n"); 
    } 
    printf("]\n"); 
    /*Determine Order of Jumpers*/ 
    position_solve(n,k,X,x,order); 

    printf("--------------------------------------------\n\n"); 

    /*If A,B,C Permutation find inverse*/ 
    if(((int)(order[k*n])==1) && ((int)(order[k*n+1])==2)){ 
     inverse(n,A,X,b); 
    } 
} 
/* Free allocated memory */ 

FREE(A); 
FREE(b); 
FREE(x); 
FREE(X); 
FREE(order); 
FREE(length); 
FREE(m); 

return 0; 
} 

void iter_solve(int n, double A[], double b[], double x[]) 
{ 
int i, j, k = 0; 
double sum, delta = 0.2, x_store; 

/*Check for division by zero and guess X=Zeros*/ 
for(i=0;i<n;i++){ 
    x[i] = 0; 
    if(fabs(A[i*n + i]) < ZERO){ 
     //exit if division by zero occurs 
     printf("Division by zero occurs. Preconditioning A matrix may be required."); 
     exit(EXIT_FAILURE); 
    } 
} 

/*Perform Gauss-Seidel Iteration*/ 
while((delta>TOL) && (k<MAX_ITER)){ 
    for(i = 0; i < n; i++){ 
     x_store = x[i]; 
     sum = 0; 
     /*Sum for j<i*/ 
     for(j = 0;(j < i); j++){ 
      sum += A[i*n +j]*x[j]; 
     } 
     /*Sum for i>j*/ 
     for((j=i+1);j<n;j++){ 
      sum += A[i*n +j]*x[j]; 
     } 
     //Determine X value for current iteration 
     x[i] = (b[i]- sum)/A[i*n + i]; 

     /*Find the residual difference using L1-norm*/ 
     if((k>0) && (delta>((fabs(x[i] - x_store)/fabs(x[i]))))){ 
      delta = fabs(x[i] - x_store)/fabs(x[i]); 
     } 
    } 
    k++; 
} 
/*Print Number of iterations*/ 
printf("\nNumber of iterations: %d using a tolerance of %f \n",k,TOL); 
} 

void position_solve(int n,int k,double X[], double x[],double order[]) 
{ 
int j, position; 
double length = 0; 
for (j = 0; j < n; j++) { 
      //printf("%f ", X[j]); 
      position = (int)(order[k*n +j]); 
      length += X[j] + x[position]; 
      printf("Bungee Jumper %i: %lf meters\n",position,length); 
      /*Reset X vector to zero*/ 
      X[j] = 0; 
     printf("\n"); 
    } 
} 

void inverse(int n, double A[],double X[],double b[]) 
{ 
int i,j; 
double *Inv_A; 
ALLOCATE(Inv_A, double, n * n); 

for(i=0;i<n;i++){ 
    for(j=0;j<n;j++){ 
     if(i==j){ 
      b[i]=1; 
     } 
     else{ 
      b[i]=0; 
     } 
    } 
    iter_solve(n,A,b,X); 
    for(j=0;j<n;j++){ 
     Inv_A[i*n +j] = X[j]; 
    } 
} 
printf("\nInverse A = [\n"); 
for(i=0;i<n;i++){ 
    for(j=0;j<n;j++){ 
     printf(" %lf ",A[i*n +j]); 
    } 
    printf("\n"); 
} 
printf(" ]\n"); 
FREE(Inv_A); 
} 
void swap(double *p1,double *p2) 
{ double temp; 
temp = *p1; 
*p1 = *p2; 
*p2 = temp; 
} 

int noofpermutations(int n) 
{ int permutations=1,i; 
for(i=1;i<=n;i++) 
permutations=permutations*i; 
return permutations; 
} 

void next(int n,double a[]) 
{ int i; 
for(i=0;i<n;i++){ 
if(count < noofpermutations(n)){ 
    a[(count+1)*n + i] = a[count*n +i]; 
} 
} 
count++; 
} 

void permute(int n, double a[]) 
{ int j; 
while(count<noofpermutations(n)){ 
for(j=0;j<n-1;j++) 
{ swap(&a[count*n + j],&a[(count*n) + (j+1)]); 
next(n,a); 
} 
swap(&a[(count*n)],&a[(count*n) + 1]); 
next(n,a); 
for(j=n-1;j>0;j--) 
{ swap(&a[(count*n)+ j],&a[(count*n) + (j-1)]); 
next(n,a); 
} 
swap(&a[(count*n) + (n-1)],&a[(count*n) + (n-2)]); 
next(n,a); 
} 
} 

void permutation(int n,double a[]) 
{ 
permute(n,a); 
count = 0; 

allocate.h 

/* 
* allocate.h 
* 
* Dynamic memory allocation macros 
*/ 

#ifndef _allocate_h_ 
#define _allocate_h_ 

#include <stdio.h> 
#include <stdlib.h> 

#define ALLOCATE(VAR,TYPE,SIZE) \ 
    { \ 
(VAR) = (TYPE *) calloc ((SIZE), sizeof(TYPE)); \ 
if ((VAR) == NULL) { \ 
    fprintf (stderr, "ALLOCATE: Memory allocation failed (%s:%d) [%d]\n", __FILE__, __LINE__, (SIZE)); \ 
    exit (EXIT_FAILURE); \ 
} \ 
    } 


#define FREE(VAR) \ 
{ \ 
free ((VAR)); \ 
(VAR) = NULL; \ 
} 

#endif 

/* 
* iter.h 
* 
* Routine for solving square systems of linear equations with 
* multiple right-hand sides AX=B using Gauss-Seidel iterative methods 
*/ 


/* Zero tolerance for double precision */ 
#define ZERO 1.0E-12 

/* Tolerance for iteration relative change */ 
#define TOL 0.01 

/* Maximum number of iterations */ 
#define MAX_ITER 500 

void iter_solve(int n, double A[], double b[], double x[]); 
/* 
* Iterative solver, x = (b - LU * xp)/D 
* Input: 
* n = size of matrix A 
* A = factorised A matrix, (nxn) stored by row 
* b = right-hand side vector, (nx1) 
* Output: 
* x = solution vector, (nx1) 
* Failure scenarios: 
* Division by "zero" 
*/ 

+0

최대한 멀리 볼 수있는, allocate.h 올바르게 정의 ALLOCATE; '(VAR) = (TYPE *) calloc ((SIZE), sizeof (TYPE))에 TYPE 주위에 빠진() 것을 막는다. \'. 당신이 우리의 기억을 실행하고있을 가능성은 희박합니다. 프로그램을 컴파일하고 실행하는 방법을 묻습니다. – Ram

+0

저는 Visual C++ 2010을 사용합니다. 보통 Ctrl-f5를 사용하여 실행합니다. 또는 중단 점을 사용하는 경우 f5. –

+0

안녕하세요 저는 일부 중단 점을 사용하고 FREE()를 사용할 때의 오류 범위를 좁혔습니다. 그게 도움이되는지 모르겠다. ... –

답변

0

자신의 오류가 디버거에서 발생하면이 프로그램에 어디에, 당신을 말해야한다 그게 발생합니다 - 잘하면이 메모리 위치가 손상되고 식별 할 수 있습니다.

주소는 디버거에서 프로그램을 다시 시작하고 할당이 발생한 후에 중단 점을 설정 한 다음 해당 메모리 위치에 데이터 중단 점을 설정하고 누가이를 휴지통에 있는지 확인합니다. 프로젝트의 연결을위한 런타임 라이브러리가 다른 경우

+0

감사합니다. 그게 문제를 해결하고 엄청난 시간을 절약 해주었습니다. –

0

DLL을 힙 손상이 발생할 수 있습니다 라이브러리의