由于循环

时间:2018-01-07 12:09:10

标签: c memory-management

所以我在这里有这个循环:

/* loop */
omp_set_dynamic(0);
#pragma omp parallel num_threads(1)
#pragma omp for ordered private(iterationPoints, normalizedPoints, grid)
for(iterations = maxIter; iterations >= minIter; iterations -= stepSizeIter){

        /* calculate iterationPoints */
        iterationPoints = (double **) malloc(iterations *sizeof(double *));
        int i;
        for(i = 0; i < iterations; i++){
            iterationPoints[i] = (double *) malloc(DIMS *sizeof(double));
        }
        calcuTraj(iterationPoints,a,b,c,x,y,z,h,iterations, bounds, (iterations == maxIter));

        /* normalize Data */
        normalizedPoints = (double **) malloc(iterations *sizeof(double *));
        for(i = 0; i < iterations; i++){
            normalizedPoints[i] = (double *) malloc(DIMS * sizeof(double));
        }

        #pragma omp ordered
        printf("%d %f  %f  %f  %f  %f  %f\n",iterations,bounds[0][0] ,bounds[0][1], bounds[1][0], bounds[1][1], bounds[2][0], bounds[2][1]);

        normalize(iterationPoints, normalizedPoints, bounds, iterations); 

        /* creating 3D Array for the grid of boxes in space*/

        /* setting minimum for sidelength of the grid */
        double minGridSideLength = 1; 
        /* calculating array size */
        int boxesPerDim = ceil(minGridSideLength/epsion) +1;

        //printf("boxesPerDim: %d \n", boxesPerDim);

        /* create grid array */
        grid = (bool ***) malloc(boxesPerDim *sizeof(bool **));

        int j_X, j_Y; 
        for(j_X = 0; j_X < boxesPerDim; j_X++){

            grid[j_X] = (bool **) malloc(boxesPerDim *sizeof(bool *));

            for(j_Y = 0; j_Y < boxesPerDim; j_Y++){
               grid[j_X][j_Y] = (bool *) calloc(boxesPerDim,sizeof(bool *));
            }
        }   

        /* count hitted boxes */
        int boxesHit = boxCount(normalizedPoints, grid, iterations, epsion, boxesPerDim);

        #pragma omp ordered
        fprintf(file,"%d  %d\n", iterations, boxesHit);
        //printf("%d \n",boxesHit);


        /* free storage */
        free(iterationPoints);
        free(grid);
        free(normalizedPoints);

}

我将线程数设置为1,因此没有多线程会导致高迭代的爆炸ram。因此,在此配置中,循环将逐步运行。函数'calculatedTraj(..)'计算'迭代点'。如果我将它从minIter = 20 * 10 ^ 6运行到maxIter = 50 * 10 ^ 6次迭代,其中stepsize = 10 * 10 ^ 6我的ram爆炸并且该过程被杀死。但是,如果我运行minIter = maxIter = 50 * 10 ^ 6的程序,它正在工作,并且ram很好。 那么为什么用for循环不可能做到这一点,因为在每个循环部分的末尾我释放了分配的内存,那么为什么ram会爆炸呢?

1 个答案:

答案 0 :(得分:0)

grid[j_X] = (bool **) malloc(boxesPerDim *sizeof(bool *));
grid[j_X][j_Y] = (bool *) calloc(boxesPerDim,sizeof(bool *));

你还没有释放这些。

与一些结构类似:

struct whatever {
int something
char *stringly
};

struct whatever *whtvr = malloc(sizeof(struct whatever));
whtvr->stringly = malloc(strlen("whatever") + 1);

...

在放弃结构的内存之前,你必须释放字符串的内存。

free(whtvr->stringly);
free(whtvr);