0

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?

4
  • 1
    I bet some dollars that work is a (non-static) local variable... Commented Nov 20, 2013 at 18:53
  • Also, IDK how much of a problem that could be, but 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... Commented Nov 20, 2013 at 18:57
  • Also, show us some compilable code that actually fails. The question is too abstract as it is now. Commented Nov 20, 2013 at 19:11
  • explain what exact problem Commented Nov 20, 2013 at 19:28

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Your advice were very usefull too
0

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);

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.