这是否意味着内存泄漏?

时间:2019-06-05 09:56:11

标签: c++ memory-leaks crt

我有一个c ++程序,我想在运行时跟踪堆内存

int MyFunction(){
  //do function logic here
  //do function logic here

 .....................
  //Check memory state in heap at the end of function
  _CrtMemState crtMemState;
  _CrtMemCheckpoint(&crtMemState);
   printf("Memory: %d\n",crtMemState.lTotalCount);

}

int main(){
  while(true){//Yes infinitive for long run test
   MyFunction();
  }
}

我得到了记忆的结果:

Memory: 47435440
Memory: 76571670
Memory: 105710436
Memory: 135412510
Memory: 164726468
Memory: 194256398
Memory: 223569972
......

这意味着每次执行函数时内存都会增加。 这是否意味着MyFunction()有泄漏? 我尝试了一些方法,例如视觉泄漏检测器或_CRT *相关函数,但没有有关泄漏的报告。我的程序随着内存的运行而增加(我使用PerfMonitor进行检查)

1 个答案:

答案 0 :(得分:2)

这并不意味着它会泄漏

如果我们看这段代码:

#include <iostream>
#include <vector>

int MyFunction(){
    // no leak
    static std::vector<int> v;
    v.push_back(1);
    std::cout << "memory used : " << v.size() * sizeof(int) << std::endl;
}

int main(){
  while(true){//Yes infinitive for long run test
   MyFunction();
  }
}

这将产生:

memory used : 40140
memory used : 40144
memory used : 40148
File size limit exceeded

向量有时会要求超出PC所能提供的内存,程序将崩溃。

因此,如果您的MyFunction被调用很多次,您的程序也会崩溃。


但是不是总是泄漏。可能是,可能不是。

在我的代码中没有泄漏,向量将在主循环之后被销毁(由于while(1)而不会,但是我们知道如何清除内存)。

泄漏是我们无法销毁的记忆,因为我们“迷失”了它所在的位置。像这样:

int MyFunction(){
    // leak
    new int();
}

在这里我们无法在此delete上呼叫int,因为它的地址已久丢失。


您可以阅读有关语法与语义内存泄漏 here的段落。