Riccardo Cipolleschi
Riccardo Cipolleschi

Reputation: 237

C++ Corrupted heap without using pointers or arrays

I'm developing a C++ console application to dynamically load a DLL.

The application can successfully invoke one of the DLL's functions. But, at the end of the execution, a corrupted heap exception is thrown. The specific value is:

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

I wonder why... Here the code.

#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;
}

I don't know where it could be the problem: if the library is correctly loaded, I free it; there aren't pointers and I'm not using any buffer...

Any idea? The exception occurs only when the execution reaches the last closed curly brace...

Upvotes: 1

Views: 233

Answers (1)

mark
mark

Reputation: 5469

This seems more like a stack problem (which may be impacting the error reporting). Is your calling convention correct? CALLBACK might be __stdcall while the decoration seems to indicate __cdecl

Upvotes: 2

Related Questions