I’m writing a function that creates a file using the win32 API
void createFile(HWND hwnd, LPTSTR pszFile, PBITMAPINFO pbi, HBITMAP hBMP, HDC hDC)
I’ve also written a function that dynamically generates a file name based on the current time.
char * getFilename() {
char filename[200] = "";
char buf[40];
SYSTEMTIME st;
GetSystemTime(&st);
itoa(st.wHour, buf,10)
strcat(filename,buf);
.....
return filename;
}
I call the above function like:
createFile(hwnd, getFilename, pbi, hBMP, hDC);
Passing through the debugger, the filename is correct until after the first statement in createFile() is executed and the string suddenly becomes “ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ”
It’s clear I have some sort of type error, but I am unsure how to fix it. I am new to the win32 API and have a lot of trouble understanding the various types used, so I would appreciate any help fixing this issue
You are returning a pointer to
filename, which has been allocated on the stack insidegetFilenameand so is freed when the function returns.EDIT: To avoid confusion – the memory is allocated on the stack, not on the heap (via
mallocornew). So “it is freed” does not refer to callingfree(ordelete). Rather to the fact that it is no longer reserved. Not available for use anymore. Deallocated. Bereft of bytes. This is a non-buffer.For a solution, consider allocating the memory outside of
getFileName. This can be done on the stack by the caller, who passes the buffer as a parameter. Naturally, using a string class would be an option.