Saturday, 6 May 2017

corruption - Can you please explain this C++ delete problem?



I have the following code:



std::string F()
{
WideString ws = GetMyWideString();

std::string ret;
StringUtils::ConvertWideStringToUTF8(ws, ret);

return ret;
}


WideString is a third-party class, so are StringUtils. They are a blackbox to me. Second parameter is passed by reference.



When I step through the debugger the line return ret throws a nasty popup (Visual C++) saying that heap may be corrupted. Upon closer examination copy of the string that gets returned is OK, but the deletion of ret fails. ret contains correct value before return.



What could the converting function possibly do to cause this? Any ideas to fix?




Update:




  • Project itself is a dll

  • StringUtils is a lib

  • Project is compiled against Multithreaded CRT (not debug, not dll)

  • Program seems to run fine when run outside of Visual Studio


Answer





  1. If StringUtils was compiled separately (e.g., with a different compiler version), you may have a conflict in the object layout.

  2. If StringUtils is in a DLL, you have to ensure that both it and the main program are compiled to use the standard library in a DLL. Otherwise, each module (executable and DLL) will have its own heap. When StringUtils tries to play with data in the string that was allocated from a different heap, bad things happen.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...