Choose: Memory Leak or Corrupt Stack
Sunday, May 31, 2009
I’m currently in the process of adding new functionality to our theatre control software. The software was written by JB Systems (pun intended) and in my opinion was the result of putting an infinite number of monkeys at work with Visual Studio and Delphi. Today I was lucky to uncover this nice little gem :
wchar_t * newGuid(void)
{
UUID Uuid = {0};
if (UuidCreate(&Uuid) == RPC_S_OK) {
if (UuidToStringW(&Uuid, (RPC_WSTR*)&strGuid) == RPC_S_OK) {
return strGuid;
}
return L"";
}
}
If there was a record for writing as many bugs as possible in the smallest amount code, this piece would certainly qualify for it :
- if
UuidCreatefails the return is undefined - if
UuidToStringWfails the return is static memory (L"") - Otherwise the return is a newly allocated string which should be freed by the caller
When using this function you have to choose between 2 defects :
- Free the memory returned by the function and risk segmentation faults or stack corruption
- Don’t free the memory returned by the function and leak memory after each call