-1

I have a c++ program and I want to tracking the heap memory when running

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();
  }
}

I got the result of memory :

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

It's mean that the memory is increase for each function execution. Does this mean MyFunction() has leak? I tried some method like visual leak detector or _CRT* relate function but have no report about leak. My program running with memory increase by time ( I used PerfMonitor to check)

Ryo
  • 995
  • 2
  • 25
  • 41
  • Take a few snapshots of you memory in Visual Studio debugger and find out what exactly is eating up your memory. There is no way for us to diagnose you problem based on your description. We are not psychics. – Dan M. Jun 05 '19 at 10:21

1 Answers1

2

It doesn't mean it leaks

If we look at this code :

#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();
  }
}

this will produce :

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

The vector will, at some time, ask for more memory than the PC can give, and the program will crash.

So if your MyFunction will be called an huge number of time, your program will crash too.


But it's not always a leak. May be, May be not.

In my code there is no leak, and the vector will be destroy after the main (well no because of the while(1) but we know how to clean the memory).

A leak is a memory we can't destroy anymore because we "lost" where it is. Like this :

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

Here we can't call delete on this int because its address is long lost.


You may read the paragraph about Syntactic vs Semantic Memory Leaks here.

Martin Morterol
  • 2,560
  • 1
  • 10
  • 15