不使用指针或数组的 C++ 损坏堆

标签 c++ exception cin heap-corruption buffer-overrun

我正在开发一个 C++ 控制台应用程序来动态加载 DLL。

应用程序可以成功调用 DLL 的其中一个函数。但是,在执行结束时,会抛出损坏的堆异常。具体值为:

Stack cookie instrumentation code detected a stack-based buffer overrun.

我想知道为什么...这是代码。

#include <iostream>
#include <string>
#include "windows.h"

using namespace std;

typedef DOUBLE(CALLBACK* DllFunc)(DOUBLE, DOUBLE);

int _tmain(int argc, _TCHAR* argv[])
{    
    HINSTANCE hDLL;               // Handle to DLL
    DllFunc dllFunc1;
    DOUBLE p1 = 2.0, p2 = 4.0, r;
    wstring dllName;
    string functionName;

    cout << "Insert the dll name: " << endl;
    getline(wcin, dllName);
    cout << "Insert the function name:" << endl;
    getline(cin, functionName);

    cout << "Insert the first value: " << endl;
    cin >> p1;
    cout << "Insert the second value" << endl;
    cin >> p2;

    hDLL = LoadLibrary(dllName.c_str());
    if (hDLL != NULL)
    {
        cout <<  "DLL loaded: " << hDLL << endl;
        functionName = "?" + functionName + "@MyMathFuncs@MathFuncs@@SANNN@Z";
        dllFunc1 = (DllFunc)GetProcAddress(hDLL, functionName.c_str());
        if (!dllFunc1)
        {
            // handle the error
            FreeLibrary(hDLL);
            cout << "Function not found!" << endl;
        }
        else
        {
            // call the function
            r = dllFunc1(p1, p2);
            cout << "The result is: " << r << endl;
            FreeLibrary(hDLL);
        }               
    }
    else {
        cout << "Dll not found" << endl;
    }
    cout << "Press any key to exit." << endl;
    int i;
    cin >> i;
    return 0;
}

我不知道问题出在哪里:如果库加载正确,我就释放它;没有指针,我没有使用任何缓冲区...

有什么想法吗?仅当执行到最后一个闭合的大括号时才会发生异常...

最佳答案

这看起来更像是堆栈问题(可能会影响错误报告)。您的调用约定是否正确? CALLBACK 可能是 __stdcall 而装饰似乎表明 __cdecl

关于不使用指针或数组的 C++ 损坏堆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26379942/

相关文章:

Java调用函数两次时出现越界异常?

java - 如何在 vaadin 7 中正确浏览身份验证 View

c# - Roslyn 脚本引擎在用作委托(delegate)时不会抛出运行时异常

c++ - std::cin 真的很慢

c++ - 如何读取用户输入的逗号分隔整数?

c# - 创建 COM 接口(interface)指针在开发机器上有效,但会导致应用程序在其他机器上崩溃

c++ - 用 boost::asio::io_service 替换 select()

c++ - 使用来自 CreateFile 的有效句柄来自 ReadFileEx 的无效句柄错误

c++ - 无效数字总是降为 0?

c++ - 收到有关默认构造函数的错误,我不知道为什么 - C++