views:

504

answers:

3

I've got a structure as follows:

typedef struct
{
    std::wstring DevAgentVersion;
    std::wstring SerialNumber;

} DeviceInfo;

But when I try to use it I get all sorts of memory allocation errors.

If I try to pass it into a function like this:

GetDeviceInfo(DeviceInfo *info);

I will get a runtime check error complaining that I didn't initialize it before using it, which I seemed to have fixed with:

DeviceInfo *info = (DeviceInfo*)malloc(sizeof(DeviceInfo));

But then, in the function, when I try to set either of the structures stings, it complains that I'm trying to access a bad pointer when trying to set a value to the string.

What is the best way to initialize this structure (and all of it's internal strings?

+8  A: 
Marcin
+1  A: 

std::wstring creates an object, and objects need to be constructed. By using malloc, you bypassed the constructor for your structure, which would include constructors for all the members.

The error you're getting is from std::wstring trying to use one of its own members that is still uninitialized.

You can use new instead of malloc, but probably the best solution is to use a local temporary variable and pass its address to the function.

DeviceInfo info;
GetDeviceInfo(&info);
Mark Ransom
+1  A: 

Add the function to the struct:

struct DeviceInfo
{
    std::wstring DevAgentVersion;
    std::wstring SerialNumber;
    WhatEverReturnType GetDeviceInfo() {
        // here, to your calculation. DevAgentVersion and SerialNumber are visible.
    }
};

DeviceInfo d; WhatEverReturnType e = d.GetDeviceInfo();

Note the typedef struct { ... } name; pattern is not needed in C++. If you for some reason have to use a free function for this, use reference:

WhatEverReturnType GetDeviceInfo(DeviceInfo &info) {
    // do your calculation. info.DevAgentVersion and info.SerialNumber are visible.
}

DeviceInfo d; WhatEverReturnType e = GetDeviceInfo(d);
Johannes Schaub - litb