在进程中调用 DLL 接口触发 dll 模块中的堆栈损坏错误

时间:2021-02-22 12:43:40

标签: c++ pointers exception dll mfc

我有一个在 VS 2019 环境中开发的 DLL。

它有以下接口。

GetValue(char* charPtr);
{
     strcpy_s((char*)charPtr, sizeof(strSrc), strSrc.c_str());
}

DLL 中的接口声明

extern "C" __declspec(dllexport) GetValue(char* node);

我在 VS2008 环境中创建的其中一个控制台 exe 中使用了上述接口,如下所示。

char* charPtr = new char[size + 1];
getValue(charPtr);
delete [] charPtr;

在 EXE 中调用 GetValue 后,我在 charPtr 中获得了正确的值,但是当我尝试删除 charPtr 时,它抛出异常。

Console error string - "This may be due to a corruption of the heap, which indicates a bug in XXX.exe or any of the DLLs it has loaded"

如上所示,我已在 EXE 本身中分配和取消分配内存,但仍然遇到此错误。 如果我只注释掉 getValue,删除工作就好了。

了解如果在不同的环境中创建二进制文件,这些问题是预期的,就像这里的情况。但是尝试了所有这些线程中提到的解决方案,但无济于事。

上面的代码/方法有什么问题?

好吧,即使我调用没有任何参数的 DLL 接口也会导致问题。现在它抛出以下错误

Run-time Check Failure #2 - Stack around the variable 'oss_' was corrupted.

1 个答案:

答案 0 :(得分:3)

GetValue() 中,您传递的是字符串对象的大小而不是实际大小。由于你的接口只提供了一个没有任何大小的指针,DLL函数甚至不知道它可以使用多少内存,所以这已经是一个错误的决定。

你的界面应该是:

extern "C" __declspec(dllexport) size_t GetValue(char* node, size_t nodeLen);

size_t GetValue(char* charPtr, size_t bufferlen);
{
     // Return the required size but don't copy as memory is to small
     if (bufferlen < strSrc.length()+1)
         return strSrc.length()+1;
         
     strcpy_s((char*)charPtr, bufferlen, strSrc.c_str());

     return strSrc.length();
}

然后你可以像这样使用它:

char* charPtr = new char[size + 1];
size_t len = size+1;
if((len = GetValue(charPtr, len)) > size+1)
{
    // Error, memory to small;
    delete [] charPtr;
    charPtr = new char[len];
    GetValue(charPtr, len);
}
delete [] charPtr;

size_t len = 0;
// Ask for required size
len = GetValue(charPtr, len);
char* charPtr = new char[len];
GetValue(charPtr, len);
delete [] charPtr;
相关问题