Mic*_*uth 3 c++ string crash xcode memset
我的代码适用于Windows,但现在我使用Xcode 3.2.5 C/C++编译器版本GCC 4.2移植到MAC,它崩溃了.
我把它缩小到了一个memset电话.如果我注释掉memset它的工作原理,如果我把它放回代码崩溃.
我的头文件中有一个看起来像这样的结构:
typedef struct 
{
    int deviceCount;
    struct 
    {
        #define MAX_DEVICE_ID 256
        #define MAX_DEVICE_ENTRIES 10
        std::string deviceId;   // Device name to Open
        TransportType   eTransportType;
    } deviceNodes[MAX_DEVICE_ENTRIES];
} DeviceParams;
然后在cpp文件中我有这个:
DeviceParams Param;
memset(&Param, nil, sizeof(Param));
......后来我有这个:
pParam->deviceNodes[index].deviceId = "some string"; // <----- Line that crashes with memset
就像我之前说的,如果我删除memset调用一切正常.如果我在调用memset之前查看调试器,我的结构中的字符串是\ 0,而在memset之后它们是nil.
为什么nil字符串在赋值行上崩溃而且只在MAC上崩溃?
谢谢.
Set*_*gie 14
你deviceId通过memset全面覆盖来覆盖内部数据; 不要做任何事情memset,除了POD数据类型.这是C++,我们有构造函数.您的代码应如下所示:
struct DeviceParams
{
    int deviceCount;
    struct DeviceNode
    {
        DeviceNode() : eTransportType() { } // initialise eTransportType
                                            // to 0, deviceId initialises itself
        static const int MAX_DEVICE_ID = 256;
        static const int MAX_DEVICE_ENTRIES = 10;
        std::string deviceId; // Device name to Open
        TransportType eTransportType;
    } deviceNodes[DeviceNode::MAX_DEVICE_ENTRIES];
};
然后
DeviceParams Param;
// get a pointer to Param in pParam
pParam->deviceNodes[index].deviceId = "some string";
| 归档时间: | 
 | 
| 查看次数: | 1947 次 | 
| 最近记录: |