2011-12-04 5 views
1

가능한 중복 : 배열에 포인터를 놓을 때 프로그램이 충돌합니다. 이유가 무엇입니까?

내 프로그램이 충돌
Is this C-program correct(pointers and arrays)?

내가 결국 mallocated 배열을 확보. 왜? 또한, 나는 그것을 처음에 할당하는 방법에 100 % 아니에요. 프로그램은 의도대로 작동하지만, 포인터를 놓으면 충돌이 발생합니다.

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

/* Approximates a solution to a differential equation on the form: 
    y'(t) + ay(t) = x(t) 
    y(0) = b 
*/ 
double* runge_kutta_2nd_order(double stepSize, double a, double b, double (*x) (double), double upto) 
{ 
    int resultSize = ((int) (upto/stepSize)) + 1; 
    double yt = b; 
    double time; 
    double k1,k2,ystar1,ystar2; 
    int index = 1; 

    double *results = (double*) malloc(resultSize * (sizeof(double))); 
    if(results == NULL) 
     exit(0); 

    results[0] = b; 

    for(time = 0; time <= upto; time += stepSize) 
    { 
     k1 = x(time) - a * yt; 
     ystar1 = yt + stepSize * k1; 
     k2 = x(time + stepSize) - a * ystar1; 
     ystar2 = yt + (k1 + k2)/2 * stepSize; 
     yt = ystar2; 
     results[index] = ystar2; 
     index++; 
    } 
    return results; 
} 

void free_results(double *r) 
{ 
    free(r); 
    r = NULL; 
} 


double insignal(double t) 
{ 
    return exp(t/2)*(sin(5*t) - 10*cos(5*t)); 
} 



int main(void) 
{ 
    int i; 
    double *res = runge_kutta_2nd_order(0.01,-1,0,&insignal,10); 
    printf("\nRunge Kutta 2nd order approximation of the differential equation:"); 
    printf("\ny'(t) - y(t) = e^(t/2) * (sin(5t) - 10cos(5t))"); 
    printf("\ny(0) = 0"); 
    printf("\n0 <= t <= 10"); 

    for(i=0; i<1001; i++){ 
     printf("\ni = %lf => y = ", 0.01*i); 
     printf("%lf", res[i]); 
    } 
    printf("\n"); 

    free_results(res); 

    return 0; 
} 
+3

다음과 같이 할당하면 : 'double * results = malloc (resultSize * sizeof (* results));'형식 이름을 모두 쓸 필요가 없습니다. –

+0

고마워,하지만 포인터가 double 형으로 캐스팅되지 않습니까? –

+0

C에서 포인터를 캐스팅 할 필요가 없습니다. 변환은 암시 적입니다. –

답변

1

runge_kutta_2nd_order에 힙 오버 플로우가 있습니다. 조심스럽게 루프를 점검하여 index < resultSize이 항상 유지되는지 확인하십시오.

+0

감사합니다. . 전에 할당 된 배열 밖에서 썼습니다. –

관련 문제