I've run into a kind of strange situation: I have a function that takes a pointer-to-a-pointer (getting a string from a Win32 API call) and it works as expected, but with a memory leak I'm not sure how to fix. The string is allocated on the heap, but when I try to free it, Visual Studio shows a really cryptic "heap corrupt" message box. I get the gist of what it's saying - it doesn't like my call to free() because {reasons}, but I'm not sure I understand what those {reasons} are (and it won't let me copy the message box text with Control-C, so sorry I don't have the gibberish lol). But here's the code:
Code:
bool myFunction(char** output) {
// NOTE: Before I did this part, I did all the usual stuff
// required (OpenClipboard, GetClipboardData etc.)
// Lock the handle to get the actual text pointer
char* pszText = (char *)(GlobalLock(hData));
if (pszText == NULL) return false;
// Copy the data into our output variable
size_t length = strlen(pszText) + 1;
char* data = (char*)malloc(length);
if (data == NULL) {
CloseClipboard();
return false;
}
data[length] = NULL; // This was due to another weird VS error; apparently the Win32 calls don't null-terminate clipboard data automatically, so I'm having to do it manually here. Could be the culprit, but that's unlikely because commenting this out didn't fix the problem I'm talking about (just pointing out that it exists lol)
strncpy_s(data, length, pszText, length); // I read that putting "_TRUNCATE" as the last parameter might prevent the error about the string not being NULL-terminated... you can probably tell by now I'm a Linux guy; there are a lot of "Microsoft-isms" that don't make sense to those of us who only know standard C. :D
*output = data; // Could it be this? Am I missing an "&" here? I mean the code works (compiles and runs as expected) but I'm just not sure where/how the memory needs to be free()d lol
// Release the lock, release the clipboard and we're done
if (GlobalUnlock(hData) || !CloseClipboard()) {
// NOTE: There was some other logging in here, but this area is never reached so I cut that out
return false;
}
return true;
}
// And now in main()
char* clipboard = NULL;
myFunction(&clipboard);
// Again, NULL-check removed
printf("Clipboard contents: \"%s\")\r\n", clipboard);
if (clipboard != NULL) free(clipboard); // Visual Studio MeltDown 2021.0 :D
Not sure what to make of this one. It's a tolerable memory leak for the project at hand, but I'd really like to see if I can find a way to patch it. If I free it in myFunction, then it's not available to main(); if I free it in main(), VS has kittens. So....?
PS: Sorry the whole thing is in a code tag - apparently the forum's automated checker thinks I put code somewhere else besides where I had the tags originally. Man, systems love to spew errors in my face today.