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?
You should use
newinstead ofmalloc, to assure the constructor gets called for theDeviceInfoand its containedwstrings.In general, it’s best to avoid using
mallocin C++.Also, make sure to
deletethe pointer when you’re done using it.Edit: Of course if you only need
infoin the local scope, you shouldn’t allocate it on the heap. Just do this instead: