在循环中使用时,Realloc无法分配内存

时间:2019-03-20 04:21:31

标签: c malloc realloc

我正在尝试在C语言中实现Simpson 1/3规则,并且遇到在for循环中使用malloc的问题。

我当前的实现是

int integrateSimpson(Integrate *intereg)
{
int i, j, iLoop, last;

double *tempOne = (double *) malloc(sizeof(double) * 1);
double *tempTwo = (double *) malloc(sizeof(double) * 1);

double dx, sumOdd, sumEven, area;

double lowerLimit = intereg->lowerLimit;
double upperLimit = intereg->upperLimit;
int *intervals = intereg->intervals;
int nIntervals = intereg->nIntervals;
int method = intereg->method;

for(j = 0; j < nIntervals; j++ )
{
    printf("Number of Intervals: %d",nIntervals);
    for(iLoop = 0; iLoop < nIntervals; iLoop++){
        printf("\nIntervals: %d", intervals[iLoop]);
    }
    tempOne = (double *) realloc(tempOne, sizeof(double) * intervals[j]);
    tempTwo = (double *) realloc(tempTwo, sizeof(double) * intervals[j]);
    if(tempTwo == NULL || tempOne == NULL)
    {
        TRACE("Could not realloc memory to temporary arrays");
        return EXIT_FAILURE;
    }

    if(intervals[j] % 2 != 0)
    {
        TRACE("Found odd interval, adding 1 to make it even");
        intervals[j] = intervals[j] + 1;
    }

    dx = (upperLimit - lowerLimit) / intervals[j];
    for(i = 0; i <= intervals[j]; i++)
    {
        tempOne[i] = lowerLimit + i * dx;

        tempTwo[i] = intereg->func(tempOne[i]);
    }

    sumOdd = 0;
    sumEven = 0;

    for(i = 1; i < intervals[j]; i++)
    {
        if(i % 2 == 1)
        {
            sumOdd +=  tempTwo[i];
        }
        else
        {
            sumEven += tempTwo[i];
        }
    }
    printf("\nPassed %d time", j );
    last = intervals[j] - 1;
    area = dx / 3 * (tempTwo[0] + tempTwo[last] + 4 * sumOdd + 2 * sumEven);
    intereg->areaUnderCurve[j]  = area;
    intereg->resultMatrix[method - 1][j] = intereg->areaUnderCurve[j];
}

free(tempOne);
tempOne = NULL;

free(tempTwo);
tempTwo = NULL;
return EXIT_SUCCESS; 
}

我尝试调试此问题,发现对于intervals = {2,8,16,64},该循环即使在realloc部分上也可以正常工作,但是由于某种原因在第二次迭代中,realloc不起作用,并且遇到了段错误。我尝试通过以下方式重现此问题,但以下代码可以正常工作

int i;
double *temp;

/* Initial memory allocation */
temp = (double *) malloc(sizeof(double)*1);

/* Reallocating memory */
for(i = 0;i<10;i++)
{
   temp = (double *) realloc(temp, sizeof(double)* i);
}
free(temp);
temp = NULL;

我知道realloc基本上在分配新内存的同时释放了传递给它的指针所指向的内存。但是我在这里做什么错了? 也是在循环中使用malloc的好方法吗?

感谢任何潜在客户!

0 个答案:

没有答案