Reputation: 737
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?
Upvotes: 0
Views: 119
Reputation: 36082
You are using malloc on a struct with a C++ class std:string in it
malloc knows nothing about constructors so your string will not be initialized.
instead use new/delete and avoid using malloc/free in your C++ program
params* defaultParams = new params;
or preferably
std::unique_ptr<params> defaultParams(new params);
Upvotes: 0
Reputation: 76
I think there may be something wrong with malloc. Because malloc just allocate some memory for the object. The string in your code may excess the boundary of the the memory you allocated. So there is access violation.
Try to use new instead of malloc.
Upvotes: 1
Reputation: 355
here you use a Registry class obj which initialize value second obj, you can't initialize obj without using assignment operator overload. first you should overload the assignment.
Upvotes: 0