简体   繁体   English

C ++中初始化结构错误

[英]Error with initialization structure in C++

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 但是,当我尝试初始化“字符串”参数(或其他类型,例如myClass类型或其他类型变量)时,出现错误

"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". 我不明白,为什么不起作用“ defaultParams-> path = defaultPath”。 Can someone explain? 有人可以解释吗?

I think there may be something wrong with malloc. 我认为malloc可能有问题。 Because malloc just allocate some memory for the object. 因为malloc只是为对象分配了一些内存。 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. 尝试使用new代替malloc。

here you use a Registry class obj which initialize value second obj, you can't initialize obj without using assignment operator overload. 在这里,您使用注册表类obj来初始化第二个obj值,如果不使用赋值运算符重载就无法初始化obj。 first you should overload the assignment. 首先,您应该使分配超载。

You are using malloc on a struct with a C++ class std:string in it 您正在其中具有C ++类std:string的结构上使用malloc

malloc knows nothing about constructors so your string will not be initialized. malloc对构造函数一无所知,因此不会初始化您的字符串。

instead use new/delete and avoid using malloc/free in your C++ program 而是使用new / delete并避免在C ++程序中使用malloc / free

params* defaultParams = new params;

or preferably 或最好

std::unique_ptr<params> defaultParams(new params);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM