How to remediate Microsoft typeinfo.name() memory leaks? - c++

Microsoft has a decades old bug when using its leak check gear in debug builds. The leak is reported from the allocation made by the runtime library when using C++ type information, like typeinfo.name(). Also see Memory leaks reported by debug CRT inside typeinfo.name() on Microsoft Connect.
We've been getting error reports and user list discussions because of the leaks for about the same amount of time. The Microsoft bug could also mask real leaks from user programs. The latter point is especially worrisome to me because we may not tending to real problems because of the masking.
I'd like to try to squash the leaks due to use of typeid(T) and typeinfo.name(). My question is, how can we work around Microsoft's bug? Is there a work around available?

On the line of my suggestion in the Q's comments.
For if (valueType == typeid(int)) you can use the type_index (at least since C++11)
For type_info.name() leaking memory:
Since totally eliminating the leak doesn't seem possible, the next best thing would be reduce their number (to only one leaked per type interrogation) and, secondary, to tag them for reporting purposes. Being inside some templated classes, one can hope that the 'mem leaking' report will use the class names (or at least the source file where the allocation happened) - you can subsequently use this information to filter them out from the 'all leaked memory' reports.
So instead of using typeid(<typename>), you use something like:
"file typeid_name_workaround.hpp"
template <typename T> struct get_type_name {
static const char* name() const {
static const char* ret=typeid(T).name();
return ret;
}
};
Other .cpp/.hpp file
#include "typeid_name_workaround.hpp"
struct dummy {
};
int main() {
// instead of typeid(dummy).name() you use
get_type_name<dummy>::name();
}

Related

Determine allocation call site over time (line of code) [duplicate]

I am looking for a way to track memory allocations in a C++ program. I am not interested in memory leaks, which seem to be what most tools are trying to find, but rather creating a memory usage profile for the application. Ideal output would be either a big list of function names plus number of maximum allocated bytes over time or better yet, a graphical representation of the heap over time. Horizontal axis is time, vertical axis heap space. Every function would get it's own color and draw lines according to allocated heap bytes. Bonus points for identifying allocated object types as well.
The idea is to find memory bottlenecks/to visualize what functions/threads consume the most memory and should be targetted for further optimization.
I have briefly looked at Purify, BoundsChecker and AQTime but they don't seem to be what I'm after. Valgrind looks suitable, however, I'm on Windows. Memtrack looks promising, but requires significant changes to the source code.
My google skills must have failed me, cause it doesn't seem to be such an uncommon request? All the needed information to create a tool like that should be readily available from the program's debug symbols plus runtime API calls - no?
Use Valgrind and its tool Massif. Its example output (a part of it):
99.48% (20,000B) (heap allocation functions) malloc/new/new[], --alloc-fns, etc.
->49.74% (10,000B) 0x804841A: main (example.c:20)
|
->39.79% (8,000B) 0x80483C2: g (example.c:5)
| ->19.90% (4,000B) 0x80483E2: f (example.c:11)
| | ->19.90% (4,000B) 0x8048431: main (example.c:23)
| |
| ->19.90% (4,000B) 0x8048436: main (example.c:25)
|
->09.95% (2,000B) 0x80483DA: f (example.c:10)
->09.95% (2,000B) 0x8048431: main (example.c:23)
So, you will get detailed information:
WHO allocated the memory (functions: g(), f(), and main() in above example); you also get complete backtrace leading to allocating function,
to WHICH data structure the memory did go (no data structures in above example),
WHEN it happened,
what PERCENTAGE of all allocated memory it is (g: 39.7%, f: 9.95%, main: 49.7%).
Here is Massif manual
You can track heap allocation as well as stack allocation (turned off by default).
PS. I just read that you're on Windows. I will leave the answer though, because it gives a picture of what you can get from a possible tool.
Microsoft have well documented memory tracking functions. However, for some reason they are not really well-known in the developer community. These are CRT debug functions. Good starting point will be CRT Debug Heap functions.
Check the following links for more details
Heap state reporting functions
Tracking heap allocation requests. Probably this is the functionality that you are looking for.
For a generic C++ memory tracker you will need to overload the following:
global operator new
global operator new []
global operator delete
global operator delete []
any class allocators
any in-place allocators
The tricky bit is getting useful information, the overloaded operators only have size information for allocators and memory pointers for deletes. One answer is to use macros. I know. Nasty. An example - place in a header which is included from all source files:
#undef new
void *operator new (size_t size, char *file, int line, char *function);
// other operators
#define new new (__FILE__, __LINE__, __FUNCTION__)
and create a source file with:
void *operator new (size_t size, char *file, int line, char *function)
{
// add tracking code here...
return malloc (size);
}
The above only works if you don't have any operator new defined at class scope. If you do have some at class scope, do:
#define NEW new (__FILE__, __LINE__, __FUNCTION__)
and replace 'new type' with 'NEW type', but that requires changing a lot of code potentially.
As it's a macro, removing the memory tracker is quite straightforward, the header becomes:
#if defined ENABLED_MEMORY_TRACKER
#undef new
void *operator new (size_t size, char *file, int line, char *function);
// other operators
#define NEW new (__FILE__, __LINE__, __FUNCTION__)
#else
#define NEW new
#endif
and the implementation file:
#if defined ENABLED_MEMORY_TRACKER
void *operator new (size_t size, char *file, int line, char *function)
{
// add tracking code here...
return malloc (size);
}
endif
Update: to the answer of #Skizz
Since C++20, we can use std::source_location instead of macros like __FILE__ and __LINE__.
(As this is a major simplification, I believe that it deserves a seperate answer).
On Xcode, you can use Instruments to track allocations, VM usage, and several other parameters. Mostly popular among iOS developers, but worth a try.
On Mac OS X, you can use the code profiling tool Shark to do this, IIRC.
"A graphical representation of the heap over time" - close to what you are looking for is implemented in Intel(R) Single Event API, details can be found in this article (its rather big to put it here).
It shows you timeline of per-block-size allocations and allows to add additional mark up to your code to understand the whole picture better.
The Visual Studio IDE has built-in heap profiling support (since 2015), which is probably the easiest to start with. It has graphical views of heap usage over time, and can track allocations by function/method.
Measure memory usage in Visual Studio
The CRT also has debug and profile support, which is more detailed and more low-level. You could track the data and plot the results using some other tool:
CRT Debug Heap Details
In particular, look at _CrtMemCheckpoint and related functions.

AccessViolationException reading memory allocated in C++ application from C++/CLI DLL

I have a C++ client to a C++/CLI DLL, which initializes a series of C# dlls.
This used to work. The code that is failing has not changed. The code that has changed is not called before the exception is thrown. My compile environment has changed, but recompiling on a machine with an environment similar to my old one still failed. (EDIT: as we see in the answer this is not entirely true, I was only recompiling the library in the old environment, not the library and client together. The client projects had been upgraded and couldn't easily go back.)
Someone besides me recompiled the library, and we started getting memory management issues. The pointer passed in as a String must not be in the bottom 64K of the process's address space. I recompiled it, and all worked well with no code changes. (Alarm #1) Recently it was recompiled, and memory management issues with strings re-appeared, and this time they're not going away. The new error is Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
I'm pretty sure the problem is not located where I see the exception, the code didn't change between the successful and failing builds, but we should review that to be complete. Ignore the names of things, I don't have much control over the design of what it's doing with these strings. And sorry for the confusion, but note that _bridge and bridge are different things. Lots of lines of code missing because this question is already too long.
Defined in library:
struct Config
{
std::string aye;
std::string bee;
std::string sea;
};
extern "C" __declspec(dllexport) BridgeBase_I* __stdcall Bridge_GetConfiguredDefaultsImplementationPointer(
const std::vector<Config> & newConfigs, /**< new configurations to apply **/
std::string configFolderPath, /**< folder to write config files in **/
std::string defaultConfigFolderPath, /**< folder to find default config files in **/
std::string & status /**< output status of config parse **/
);
In client function:
GatewayWrapper::Config bridge;
std::string configPath("./config");
std::string defaultPath("./config/default");
GatewayWrapper::Config gwtransport;
bridge.aye = "bridged.dll";
bridge.bee = "1.0";
bridge.sea = "";
configs.push_back(bridge);
_bridge = GatewayWrapper::Bridge_GetConfiguredDefaultsImplementationPointer(configs, configPath, defaultPath, status);
Note that call to library that is crashing is in the same scope as the vector declaration, struct declaration, string assignment and vector push-back
There are no threading calls in this section of code, but there are other threads running doing other things. There is no pointer math here, there are no heap allocations in the area except perhaps inside the standard library.
I can run the code up to the Bridge_GetConfiguredDefaultsImplementationPointer call in the debugger, and the contents of the configs vector look correct in the debugger.
Back in the library, in the first sub function, where the debugger don't shine, I've broken down the failing statement into several console prints.
System::String^ temp
List<CConfig^>^ configs = gcnew List<CConfig ^>((INT32)newConfigs.size());
for( int i = 0; i< newConfigs.size(); i++)
{
std::cout << newConfigs[i].aye<< std::flush; // prints
std::cout << newConfigs[i].aye.c_str() << std::flush; // prints
temp = gcnew System::String(newConfigs[i].aye.c_str());
System::Console::WriteLine(temp); // prints
std::cout << "Testing string creation" << std::endl; // prints
std::cout << newConfigs[i].bee << std::flush; // crashes here
}
I get the same exception on access of bee if I move the newConfigs[i].bee out above the assignment of temp or comment out the list declaration/assignment.
Just for reference that the std::string in a struct in a vector should have arrived at it's destination ok
Is std::vector copying the objects with a push_back?
std::string in struct - Copy/assignment issues?
http://www.cplusplus.com/reference/vector/vector/operator=/
Assign one struct to another in C
Why this exception is not caught by my try/catch
https://stackoverflow.com/a/918891/2091951
Generic AccessViolationException related questions
How to handle AccessViolationException
Programs randomly getting System.AccessViolationException
https://connect.microsoft.com/VisualStudio/feedback/details/819552/visual-studio-debugger-throws-accessviolationexception
finding the cause of System.AccessViolationException
https://msdn.microsoft.com/en-us/library/ms164911.aspx
Catching access violation exceptions?
AccessViolationException when using C++ DLL from C#
Suggestions in above questions
Change to .net 3.5, change target platform - these solutions could have serious issues with a large mult-project solution.
HandleProcessCorruptedStateExceptions - does not work in C++, this decoration is for C#, catching this error could be a very bad idea anyway
Change legacyCorruptedStateExceptionsPolicy - this is about catching the error, not preventing it
Install .NET 4.5.2 - can't, already have 4.6.1. Installing 4.6.2 did not help. Recompiling on a different machine that didn't have 4.5 or 4.6 installed did not help. (Despite this used to compile and run on my machine before installing Visual Studio 2013, which strongly suggests the .NET library is an issue?)
VSDebug_DisableManagedReturnValue - I only see this mentioned in relation to a specific crash in the debugger, and the help from Microsoft says that other AccessViolationException issues are likely unrelated. (http://connect.microsoft.com/VisualStudio/feedbackdetail/view/819552/visual-studio-debugger-throws-accessviolationexception)
Change Comodo Firewall settings - I don't use this software
Change all the code to managed memory - Not an option. The overall design of calling C# from C++ through C++/CLI is resistant to change. I was specifically asked to design it this way to leverage existing C# code from existing C++ code.
Make sure memory is allocated - memory should be allocated on the stack in the C++ client. I've attempted to make the vector be not a reference parameter, to force a vector copy into explicitly library controlled memory space, did not help.
"Access violations in unmanaged code that bubble up to managed code are always wrapped in an AccessViolationException." - Fact, not a solution.
but it was the mismatch, not the specific version that was the problem
Yes, that's black letter law in VS. You unfortunately just missed the counter-measures that were built into VS2012 to turn this mistake into a diagnosable linker error. Previously (and in VS2010), the CRT would allocate its own heap with HeapAlloc(). Now (in VS2013), it uses the default process heap, the one returned by the GetProcessHeap().
Which is in itself enough to trigger an AVE when you run your app on Vista or higher, allocating memory from one heap and releasing it from another triggers an AVE at runtime, a debugger break when you debug with the Debug Heap enabled.
This is not where it ends, another significant issue is that the std::string object layout is not the same between the versions. Something you can discover with a little test program:
#include <string>
#include <iostream>
int main()
{
std::cout << sizeof(std::string) << std::endl;
return 0;
}
VS2010 Debug : 32
VS2010 Release : 28
VS2013 Debug : 28
VS2013 Release : 24
I have a vague memory of Stephen Lavavej mentioning the std::string object size reduction, very much presented as a feature, but I can't find it back. The extra 4 bytes in the Debug build is caused by the iterator debugging feature, it can be disabled with _HAS_ITERATOR_DEBUGGING=0 in the Preprocessor Definitions. Not a feature you'd quickly want to throw away but it makes mixing Debug and Release builds of the EXE and its DLLs quite lethal.
Needless to say, the different object sizes seriously bytes when the Config object is created in a DLL built with one version of the standard C++ library and used in another. Many mishaps, the most basic one is that the code will simply read the Config::bee member from the wrong offset. An AVE is (almost) guaranteed. Lots more misery when code allocates the small flavor of the Config object but writes the large flavor of std::string, that randomly corrupts the heap or the stack frame.
Don't mix.
I believe 2013 introduced a lot of changes in the internal data formats of STL containers, as part of a push to reduce memory usage and improve perf. I know vector became smaller, and string is basically a glorified vector<char>.
Microsoft acknowledges the incompatibility:
"To enable new optimizations and debugging checks, the Visual Studio
implementation of the C++ Standard Library intentionally breaks binary
compatibility from one version to the next. Therefore, when the C++
Standard Library is used, object files and static libraries that are
compiled by using different versions can't be mixed in one binary (EXE
or DLL), and C++ Standard Library objects can't be passed between
binaries that are compiled by using different versions."
If you're going to pass std::* objects between executables and/or DLLs, you absolutely must ensure that they are using the same version of the compiler. It would be well-advised to have your client and its DLLs negotiate in some way at startup, comparing any available versions (e.g. compiler version + flags, boost version, directx version, etc.) so that you catch errors like this quickly. Think of it as a cross-module assert.
If you want to confirm that this is the issue, you could pick a few of the data structures you're passing back and forth and check their sizes in the client vs. the DLLs. I suspect your Config class above would register differently in one of the fail cases.
I'd also like to mention that it is probably a bad idea in the first place to use smart containers in DLL calls. Unless you can guarantee that the app and DLL won't try to free or reallocate the internal buffers of the other's containers, you could easily run into heap corruption issues, since the app and DLL each have their own internal C++ heap. I think that behavior is considered undefined at best. Even passing const& arguments could still result in reallocation in rare cases, since const doesn't prevent a compiler from diddling with mutable internals.
You seem to have memory corruption. Microsoft Application Verifier is invaluable in finding corruption. Use it to find your bug:
Install it to your dev machine.
Add your exe to it.
Only select Basics\Heaps.
Press Save. It doesn't matter if you keep application verifier open.
Run your program a few times.
If it crashes, debug it and this time, the crash will point to your problem, not just some random location in your program.
PS: It's a great idea to have Application Verifier enabled at all times for your development project.

CppCheck does not detect memory leak

Have following code, but CppCheck(1.68) detects only "style" error.
AbstractTelegram *TelegramFactory::CreateGetWigWagParameterTelegram(BYTE Address_i, BYTE SubAddress_i, BYTE Tag_i)
{
SignDataWigWag *pWigWag = new SignDataWigWag();
return new SendTelegram(SubAddress_i, Tag_i, Telegram::GET_WIG_WAG,NULL,0);
}
Output:
Variable 'pWigWag' is assigned a value that is never used.
Variable 'pWigWag' is assigned a value that is never used.
Any options to tune?
I am a Cppcheck developer.
Actually.. we can't see that there is definitely a memory leak in that code.
There are classes that has automatic memory management.
Imagine for example that the SignDataWigWag constructor has such code:
SignDataWigWag::SignDataWigWag() {
instances.push_back(this);
}
then it can be deleted later by using for instance:
void deleteAllInstances() {
while (!instances.empty()) {
delete instances.back();
instances.pop_back();
}
}
This is not unusual. Some popular class libraries has lots of classes with some kind of memory management so manual delete is not needed..
cppcheck is essentially only a style-checker (and like other tools which incorporate the developer's notion of "good style", its usefulness depends on various factors).
There are suitable tools for detecting memory leaks (such as valgrind); cppcheck is not one of those. Of course, you will find differing opinions on which are the best tools, and even on what a tool is suitable for, e.g., a blog entry *Valgrind is NOT a leak checker *

Get number of blocks allocated on the heap to detect memory leaks

Is there a function available that can get the number of blocks of memory that are currently allocated on the heap? It can be Windows/Visual Studio specific.
I'd like to use that to check if a function leaks memory, without using a dedicated profiler. I'm thinking about something like this:
int before = AllocatedBlocksCount();
foo();
if (AllocatedBlocksCount() > before)
printf("Memory leak!!!");
There are several ways to do it (specific to the CRT that comes with Microsoft Visual Studio.)
One way would be to use the _CrtMemCheckpoint() function before and after the call you are interested in, and then compare the difference with _CrtMemDifference().
_CrtMemState s1, s2, s3;
_CrtMemCheckpoint (&s1);
foo(); // Memory allocations take place here
_CrtMemCheckpoint (&s2);
if (_CrtMemDifference(&s3, &s1, &s2)) // Returns true if there's a difference
_CrtMemDumpStatistics (&s3);
You can also enumerate all the allocated blocks using _CrtDoForAllClientObjects(), and a couple of other methods using the debug routines of the Visual C++ CRT.
Notes:
All these are in the <crtdbg.h> header.
They obviously work only on Windows and when compiling with VC.
You need to set up CRT debugging and a few flags and other things.
These are rather tricky features; make sure to read the relevant parts of the MSDN carefully.
These only work in debug mode (i.e. linking with the debug CRT and the _DEBUG macro defined.)

Weird Intel C++ compiler error

I'm working on this VST convolution plugin (Windows 7 64bit, VS2010) and I decided to try the Intel c++ compiler. I was in the process of optimizing the algorithm so I had a backup project in case of any screw ups and one I was doing experiments on. Both projects would compile and run with no problems. After installing the Intel compiler though the project I was experimenting on would cause a heap corruption error, so I start debugging to track down the problem but I can't find the line of code that causes it since the heap corruption error is not triggered during execution but after the termination of the DLL (there are also no access violations showed by the debugger).
At this point I start cutting out parts of the code to see if I can isolate the problem and I discover (obviously) that it was the class I was eperimenting on. Now here comes the weird part: I can change the code inside the methods but as soon as I add a variable to the backup class (the one that works fine), even an int, I get the heap corruption error, just a decleared and never referenced variable is enough.
This is the class CRTConvolver:
class CRTConvolver
{
public:
CRTConvolver();
~CRTConvolver();
bool Init(float* Imp, unsigned ImpLen, unsigned DataLen);
void doConv(float* input);
Buff Output;
int debug_test;
private:
void ZeroVars();
int Order(int sampleFrames);
template <class T> void swap ( T& a, T& b );
Buff *Ir_FFT,*Input_FFT,Output2,Tmp,Prev,Last;
float *Tail;
unsigned nBlocks,BlockLen,Bl_Indx;
IppsFFTSpec_R_32f* spec;
};
that "int debug_test;" makes the difference between a perfectly working VST module and a program that crashes on initialization from Cubase.
always for debugging purposes here are destr and constr:
CRTConvolver::CRTConvolver()
{
//IppStatus status=ippInit();
//ZeroVars();
}
CRTConvolver::~CRTConvolver()
{
//Init(NULL,NULL,NULL);
}
Here is what class Buff looks like:
class Buff {
public:
Buff();
Buff(unsigned len);
~Buff();
float* buff;
unsigned long length;
private:
void Init(unsigned long len);
void flush();
friend class CRTConvolver;
}
Buff::Buff()
{
length=NULL;
buff=NULL;
}
Buff::~Buff()
{
// flush();
}
basically this class if created and destructed does absolutely nothing, it just contains the length and buff variables. If I also bypass those two variable initializations the heap error goes away.
The software crashes on simple construction and subsequent destruction of the class CRTConvolver even though all it does is nothing, this is the part that really doesn't make sense to me...
As a side note, I create my CRTConvolver class like this:
ConvEng = new CRTConvolver[NCHANNELS];
If I declare it like this instead:
CRTConvolver ConvEng[NCHANNELS];
I get a stack corruption error around variable ConvEng.
If I switch back to Microsoft compiler the situation stays the same even when compiling and running the exact same version that could run without errors before....
I can't stress enough the fact that before installing the Intel compiler everything was running just fine, is it possible that something went wrong or there's an incompatibility somewhere ?
I'm really running out of ideas here, I hope someone will be able to help.
thanks
Going to guess, since the problem is most likely undefined behavior, but in some other place in your code:
Obey the rule of three. You should have a copy constructor and assignment operator. If you're using std containers, or making copies or assignments, without these you run into trouble if you delete memory inside the destructor.
It looks to me that the CRTConvolver default constructor (used in creating an array) is writing to memory it doesn't own. If the Intel compiler has different class layout rules (or data alignment rules), it might be unmasking a bug that was benign under the Microsoft compiler's rules.
Does the CRTConvolver class contain any instances of the Buff class?
Updated to respond to code update:
The CRTConvolver class contains four instances of Buff, so I suspect that is where the problem lies. It could be a version mismatch -- the CRTConvolver class thinks that Buff is smaller than it really is. I suggest you recompile everything and get back to us.