c++ - 这种代码更改会导致严重的内存泄漏吗?

标签 c++ visual-c++ memory-leaks

<分区>

因为我们需要从 VB6 调用下面的代码,所以我们必须更改方法的签名

int STDCALL CalcDDtable(struct ddTableDeal tableDeal, struct ddTableResults * tablep

int STDCALL CalcDDtable(struct ddTableDeal * tableDeal, struct ddTableResults * tablep

ddTableDeal 结构仅包含一个 16 字节的数组,ddTableResults 结构仅包含一个 20 字节的数组,并填充了 dll 的计算结果。

代码是从 VB6 调用的:

Declare Function CalcDDtable Lib "dds222vb6.dll" (ByRef lngDeal As Long, ByRef lngResult As Long) As Long
Dim Cards(15) As Long   
Dim Results(19) As Long
'Some code to populate the Cards array. The Results arrays contains zeroes.
lngErrorCode = CalcDDtable(Cards(0), Results(0)) 

但是,测试计算机在 150,000 次迭代后因内存不足异常而死机。这可能是由签名更改引起的吗?对我们来说,这似乎不太可能,因为 150,000 乘以 36 字节总计刚好超过 5MB 的内存。

完整的(调整后的)代码。唯一的变化是签名,ddTableDeal.cards 已在 ddTableDeal->cards 中更改。

int STDCALL CalcDDtable(struct ddTableDeal * tableDeal, struct ddTableResults * tablep) {

  int h, s, k, ind, tr, first, res;
  struct deal dl;
  struct boards bo;
  struct solvedBoards solved;

  for (h=0; h<=3; h++)
    for (s=0; s<=3; s++)
      dl.remainCards[h][s]=tableDeal->cards[h][s];

  for (k=0; k<=2; k++) {
    dl.currentTrickRank[k]=0;
    dl.currentTrickSuit[k]=0;
  }

  ind=0; bo.noOfBoards=20;

  for (tr=4; tr>=0; tr--) 
    for (first=0; first<=3; first++) {
      dl.first=first;
      dl.trump=tr;
      bo.deals[ind]=dl;
      bo.target[ind]=-1;
      bo.solutions[ind]=1;
      bo.mode[ind]=1;
      ind++;
    }

  res=SolveAllBoards4(&bo, &solved);
  if (res==1) {
    for (ind=0; ind<20; ind++) {
      tablep->resTable[bo.deals[ind].trump][rho[bo.deals[ind].first]]=
        13-solved.solvedBoard[ind].score[0];
    }
    return 1;
  }

  return res;
}

最佳答案

CalcDDtable 的函数签名不会泄漏内存。函数 CalcDDtable 中的代码有一些局部变量,这些变量在函数被调用时分配到堆栈上,并在函数返回时从堆栈中弹出。所以你的内存泄漏不在这个函数中。

关于c++ - 这种代码更改会导致严重的内存泄漏吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13081827/

相关文章:

c++ - 如何将返回类型推导、模板实例化与头文件结合起来?

c++ - 使用 istreambuf_iterator<> 将文件内容转换为字符串流

c++ - 如何在C++中为二维数组赋值

c - Execvp 内存错误

c++ - 第一次填充 QTableWidget 时,一切都很好,但是当我重新填充它时,速度明显变慢

C++ 链接器问题,是否有解决这些问题的通用方法?

c++ - 内存/线程泄漏,使用 WinSock2 开发简单的 HTTP 服务器

iphone - 苹果框架中的内存泄漏

c++ - 为什么 const 变量必须立即初始化?

visual-c++ - 一家非常小的公司的代码/文档管理