(int*) malloc(SIZE * sizeof(int)) 惨痛的教训

 

 

      在做PSO-cluster解决 SR问题时,当SIZE较小,如SIZE<=8时,程序正常运行,但是在free(mark)时出错。

      当SIZE=10或者更大时,程序在InitArea-->CandidateSS或其他函数中的q_create()中出现错误:Q->Ar始终开辟不成功:进入

     if (ptrAr == NULL)
     {
        fprintf(errLog, "can't malloc for Q->Ar in q_create\n");
        fclose( errLog );
        exit(-1);
     }

   程序出现弹窗:

   “Windows 已在 pso4-26.exe 中触发一个断点。

      其原因可能是堆被损坏,这说明 pso4-26.exe 中或它所加载的任何 DLL 中有 Bug。

      原因也可能是用户在 pso4-26.exe 具有焦点时按下了 F12。

      输出窗口可能提供了更多诊断信息。”

 程序最终截止在:

  retval = HeapFree(_crtheap, 0, pBlock);

 

最终发现问题为:

   mark1 = malloc(SIZE);

   mark2 = malloc(SIZE);这两个变量的定义不正确;

   本意是想变为SIZE个int类型的数组,可是实际上,malloc括号内的size为字节数,导致内存泄露;

   应该为:

   mark1 = (int*) malloc(SIZE * sizeof(int));

   mark2 = (int*) malloc(SIZE * sizeof(int));

 

你可能感兴趣的:((int*) malloc(SIZE * sizeof(int)) 惨痛的教训)