leon22
leon22

Reputation: 5649

STATUS_STACK_BUFFER_OVERRUN with LoadLibrary

When I load iphlpapi.dll with LoadLibrary my stack buffer overrun! How can I solve this problem?!

typedef DWORD (*GetExtendedTcpTable)(PVOID, PDWORD, BOOL, ULONG, TCP_TABLE_CLASS, ULONG);   
GetExtendedTcpTable _GetExtendedTcpTable;

// load function at runtime 
HINSTANCE hstLibrary = LoadLibrary("C:\\Windows\\System32\\Iphlpapi.dll");

if(!hstLibrary)
{
    ::MessageBox(NULL,"Can't load Iphlpapi.dll!\n","Error",
            MB_OK + MB_ICONEXCLAMATION + MB_TASKMODAL);

    FreeLibrary(hstLibrary); // free memory

    exit(0);
}

// load function address from dll
_GetExtendedTcpTable = (GetExtendedTcpTable)GetProcAddress(hstLibrary, "GetExtendedTcpTable");

The loading of the lib function and executing is working fine but at some point my program throws the STATUS_STACK_BUFFER_OVERRUN exception! (some point: when I comment the string operation the error occur few lines later)

When I don't use LoadLibrary and GetProcAddress(static binding) -> no buffer overrun!

Thanks and greets,

leon22

Upvotes: 1

Views: 9888

Answers (2)

Erik
Erik

Reputation: 91320

You need to specify calling convention:

typedef DWORD (WINAPI * GetExtendedTcpTable)(PVOID, PDWORD, BOOL, ULONG, TCP_TABLE_CLASS, ULONG);   

The default calling convention in VS is __cdecl, Windows API requires __stdcall. These differ in how the stack for arguments is handled, most notably __cdecl requires the caller to clean up whereas __stdcall requires the called function to clean up.

WINAPI is defined as __stdcall

See e.g. Calling Conventions Demystified

Upvotes: 3

floyd73
floyd73

Reputation: 1240

My first guess is that you are using the wrong calling convention for the function of the library which can then lead to stack corruptions (among other strange problems that may show up only later, after the call was made). Check if you don't need to used __stdcall or something else in your function prototype..

Upvotes: 0

Related Questions