Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OS dependent C++ memory leaks?

CONTEXT

I run Valgrind on my codebase under Linux for my cross-platform library. I am trying to see if this is enough or if I should run a dynamic code analysis on Windows and Mac too

QUESTION

If my platform independent C++ code is not leaking on Linux (according to Valgrind), can I assume it is not leaking on Windows and Mac too? If no, please provide a platform independent C++ sample not leaking on Linux (according to Valgrind) but leaking on Windows and/or Mac (choose "common" compilers like those in VC++, GCC, etc).

Precision (thanks to comments and answers)

  1. I am interested in platform independent C++ code (so no #ifdef, etc);
  2. I consider C++ code I own, not third party code;
  3. I consider Valgrind as the ground-truth but I could consider any other tool. I know that no tool could detect all memory leaks.
like image 796
Korchkidu Avatar asked Mar 23 '23 14:03

Korchkidu


2 Answers

You can be pretty sure that generic code isn't leaking, but of course, if you have a decent size application, it is quite likely that SOME of your code is specific to Linux, other bits specific to Windows and some parts specific to OS X.

Those portions that are not specific to Linux will of course not be tested by Valgrind.

So if you have some piece of code that does:

#if LINUX
 char buffer[512]; 
#else
  char buffer = new buffer[2048]; 
#endif
  ... use buffer ... 

then you have a memory leak in Windows but not Linux.

Clearly, this is a trivial example, but similar things can creep into code at times.

And of course, there is the potential that using a system call of some sort in the one OS is "safe" to not close or otherwise "tell the OS you are finished", and then have a problem in another OS.

Also, as I have pointed out before, Valgrind doesn't guarantee that you haven't got issue with memory usage - it only detects things like:

 void func()
 {
     char *p = new [1700];
     ... 
     // no free of p;
 }

or

 void func()
 {
     char *p = new [1700];
     ... 
     // No free. 
     p = some_other_pointer; 
     ... 
 }

but not:

 void func()
 {
    vector<int> v;
    for(;;)
       v.push_back(1); 
 }

because the memory is still "owned" by something. Of course, this particular example is quite extreme, but you can have similar things where the code is storing something and just adding more and more items to the storage, and never removing them.

like image 92
Mats Petersson Avatar answered Mar 25 '23 03:03

Mats Petersson


valgrind helps to find flaws, but does not guarantee correctness.

You could still have undefined behaviour in your code, and that undefined behaviour could manifest itself differently on different platforms, including leaking memory on one but not the other.

like image 39
NPE Avatar answered Mar 25 '23 04:03

NPE