csp910809
csp910809
2019-12-27 20:42
采纳率: 100%
浏览 435

OpenMP 并行堆内存释放问题

malloc函数声明一个二维动态数组A,使用omp并行对A赋值,然后释放A内存时报错。在不使用并行时,不会报错。谢谢!代码如下:
void main(){

void main(){

    int i,j, Njuncs=1827;
    //创建二维数组A
    double**A = (double **)malloc(sizeof(double *)*(Njuncs + 1)); 
    for (i = 0; i < Njuncs + 1; i++)
        *(A + i) = (double  *)malloc(sizeof(double) * (Njuncs + 1)); 

#pragma omp parallel
    {
#pragma omp for
        for (i = 0; i <= Njuncs; i++)
            for (j = 0; j <= Njuncs; j++)
                A[i][j] = 1;
    }
    for (i = 0; i < Njuncs + 1; i++){
        free(*(A + i));//该步报错
        A[i] = NULL;
    }
    free(A);
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • sculxp
    sculxp 2019-12-28 09:32
    已采纳

    其实并行多重循环这么写肯定是有问题的,内部循环变量j是共享的,被多个线程同时修改,那么就很有可能超出Njuncs,发生内存越界写入,**切记循环内的变量写入是并行的**。
    应该把 j 声明为并行体中私有的,这样结果就正确了,参考如下代码:

    #include <cstdlib>
    
    int main(int argc, char* argv[]) {
        int i, j, Njuncs = 1827;
        //创建二维数组A
        double** A = (double**)malloc(sizeof(double*) * (Njuncs + 1));
        for (i = 0; i < Njuncs + 1; i++)
            *(A + i) = (double*)malloc(sizeof(double) * (Njuncs + 1));
    
    #pragma omp parallel
        {
    #pragma omp for private(j)
            for (i = 0; i <= Njuncs; i++)
                for (j = 0; j <= Njuncs; j++) {
                    A[i][j] = 1;
                }
        }
    
    #pragma omp parallel for
        for (i = 0; i < Njuncs + 1; i++) {
            free(*(A + i));//该步报错
            A[i] = NULL;
        }
        free(A);
    
        return 0;
    }
    
    点赞 评论
  • caozhy
    点赞 评论

相关推荐