开发者

Win32 Releasing Environment Variables causes Windows Breakpoint

I have a win32 c++ application & I getting all the environment variables & storing them in a map.

When I call the Win32 function FreeEnvironmentStrings() in my application I get a weird Windows Breakpoint in MSVC++. First I dont know what this means & why its occurin开发者_开发技巧g?

How can I fix my problem & what is going wrong?

This the function that I call in my main function & the one that causes the breakpoint:

std::map <tstring, tstring> GetEnvironmentVariablesEx()
{
   // Post: Get all windows environment variables & store in a
   //       map(key=env.. variable name, value=env variable value)

   std::map <tstring, tstring> envVariables;
   TCHAR* environVar = GetEnvironmentStrings();
   TCHAR* pos        = _tcschr( environVar, _T('\0') );


   // Skip over the "=::=::\0" of the environVar string
   if ( pos != NULL ) { environVar = ++pos; pos = _tcschr( environVar, _T('\0') ); }
   else return envVariables;


   // I removed the following code because its long & distracting: the error still occurs without the code
   // Code: ...use cstring functions to extract environ variables & values & store in map


   FreeEnvironmentStrings( environVar );   // Breakpoint triggered here: "Windows has triggered a breakpoint in the application. This may be due to a corruption of the heap, which indicates a bug in myApp.exe or any of the DLLs it has loaded."
   return envVariables;       
}    


You're changing what environVar points to, so you're not handing the FreeEnvironmentString function a valid environment string pointer.

Save the original environVar somewhere before modifying it and use that in the Free call.

TCHAR* tobefreeed = GetEnvironmentStrings();
TCHAR* environVar = tobefreeed;
...
FreeEnvironmentStrings( tobefreeed );


After you skip reserved characters environVar no longer points at data area allocated by GetEnvironmentStrings. This causes FreeEnvironmentStrings to fail.

Preserve original pointer intact (modify a copy if you need) and you'll solve the problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜