I have this structure in my code. 'Compilable' part of code:
#define MONITOR_TOPKEY HKEY_LOCAL_MACHINE
#define MONITOR_SUBKEY TEXT("SOFTWARE\\WMyRegistry")
struct params {
HKEY hMainKey;
LPTSTR hSubKey;
string path;
bool* runflg;
};
void _tmain(void) {
bool work = true;
string defaultPath = "HKEY_LOCAL_MACHINE";
defaultPath += "\\";
defaultPath += MONITOR_SUBKEY;
params* defaultParams = (params*) malloc(sizeof (params));
defaultParams->hMainKey = MONITOR_TOPKEY;
defaultParams->hSubKey = MONITOR_SUBKEY;
defaultParams->path = defaultPath; // HERE THERE IS A PROBLEM
defaultParams->runflg = &work;
}
When I set all parametrs (except "string") - all are good and working. But when I try to inizialize 'string' parametr (or another type instead of this, for ex myClass type or another else type variable) I have the error
"Unhandled exception at 0x0FDEEAD0 (msvcr110d.dll) in ConsoleApplication1.exe:
0xC0000005: Access violation when writing to the address 0xCDCDCDCD."
I don't understand, why doens't work " defaultParams->path = defaultPath". Can someone explain?
workis a (non-static) local variable...malloc()doesn't work well in C++, it doesn't call constructors. So a simple innocent-looking assignment may cause your program to try to deallocate garbage...