DLL:Visual Studio 2013(VC12)/应用程序:Visual Studio 2010(VC10)

我正在创建一个允许客户端访问我们系统的库。但是,当删除从dll返回的指针数组时,客户端应用程序崩溃。当删除普通指针(非数组)时,一切似乎都可以正常工作。有想法吗?我注意到,当使用VC12作为客户端应用程序时,该阵列会被删除,尽管使用VC10时会崩溃。

所以我的问题是:如果从dll返回时删除指针数组,为什么客户端应用程序崩溃,如果删除dll分配的内存不会删除系统;也是一个问题?

struct IDevice {
    virtual ~IDevice() {}
    char name[64];
};

class Device : public IDevice {
public:
    Device() {}
    ~Device() {}
};

struct ISystem {
    virtual ~IDevice() {}
    virtual Result::Value GetDevices(Collection<IDevice**>* deviceCollection) = 0;
};

class System : public ISystem {
public:
    Result::Value GetDevices(Collection<IDevice**>* deviceCollection) {
        Result::Value result = Result::Success;
        deviceCollection->collectionSize = 1;
        deviceCollection->collection = new IDevice*[1];

        IDevice* device = new Device();
        Utilities::strcpy_safe(device->name, "blackey");
        deviceCollection->collection[0] = device;
        return result;
    }
};

template<typename T>
struct Collection {
    T collection;
    int collectionSize;
};

///////// Main App ///////////

LoginInfo loginInfo;
string ip("192.168.1.2");
string u("admin");
string password("admin");
loginInfo.port = 443;
loginInfo.ssl = true;
strncpy_s(loginInfo.ipAddress, ip.c_str(), sizeof(loginInfo.ipAddress)-1);
strncpy_s(loginInfo.uname, u.c_str(), sizeof(loginInfo.uname)-1);
strncpy_s(loginInfo.password, password.c_str(), sizeof(loginInfo.password)-1);

ISystem* system = nullptr;
// SystemLogin calls into my dll which allocates memory for system OK
Result::Value result = SystemLogin(&loginInfo, &system);

Collection<IDevice**> devices;
// If the line below is uncommented, and the dll is modified to not allocate memory, but instead use this memory
// then below the delete[] devices.collection; works.
//devices.collection = new IDevice*[50];

// Makes a call into the library which populates devices
result = system->GetDevices(&devices);

for (int i = 0; i < devices.collectionSize; i++) {
    // Each item in the array is deleted OK
    delete devices.collection[i];
}

// Deleting this array of pointers crashes (see screenshots) when it's memory was allocated in the dll.
delete[] devices.collection;

// system deletes OK
delete system;

c&#43;&#43; - 删除指针数组会使调用者的应用程序崩溃-LMLPHP

c&#43;&#43; - 删除指针数组会使调用者的应用程序崩溃-LMLPHP

最佳答案

您应该检查客户端应用程序和dll是否使用相同的设置进行编译。为防止此类问题,最好采用以下两种方法之一:

  • 在客户端
  • 上分配/取消分配内存
  • 在DLL(服务器)端
  • 上分配/取消分配内存

    我会推荐#1,但我看到您正在使用#2。因此,您现在应该做的是添加system->FreeDevices(&devices);,它将释放内存-但在dll内部。

    [编辑]

    从msdn读取的引用:https://msdn.microsoft.com/en-us/library/ms235460.aspx

    重要的部分是关于可用于构建dll和客户端应用程序的不同CRT。这可能会导致您遇到的确切问题:

    关于c++ - 删除指针数组会使调用者的应用程序崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32479227/

    10-09 00:45
    查看更多