R.Koster
R.Koster

Reputation: 23

Memory overwritten after allocating array of structs

I'm trying to allocate memory for a array of structures, but after it is allocated a int that is passed in the function is set to '0'... The problem is gone when i increase the size of the array. Here is my code:

wchar_t* ISTFallSensor::JSON_EventLog(int nRecords) {
wchar_t* returnstring = new wchar_t[8192]; memset( returnstring, 0, 8192 * sizeof(TCHAR) ); 

HINSTANCE hIstDLL;
DWORD (*IST_Open)(TCHAR *, HANDLE *)                                        = 0;
DWORD (*IST_Close)(HANDLE)                                                  = 0;
DWORD (*IST_GetMotionEventLogCount)(HANDLE, DWORD, PDWORD)                  = 0;
DWORD (*IST_GetMotionEventLogRecords)(HANDLE, IST_LOG_RECORD[], int, PINT)  = 0;

hIstDLL = LoadLibrary(L"ISTAPI32.dll");
if(hIstDLL && nRecords > 0 ){
    IST_Open                        = (DWORD (__cdecl *)(TCHAR *, HANDLE *))GetProcAddress(hIstDLL, L"IST_Open");
    IST_Close                       = (DWORD (__cdecl *)(HANDLE))GetProcAddress(hIstDLL, L"IST_Close");
    IST_GetMotionEventLogCount      = (DWORD (__cdecl *)(HANDLE, DWORD, PDWORD))GetProcAddress(hIstDLL, L"IST_GetMotionEventLogCount");
    IST_GetMotionEventLogRecords    = (DWORD (__cdecl *)(HANDLE, IST_LOG_RECORD[], int, PINT))GetProcAddress(hIstDLL, L"IST_GetMotionEventLogRecords");

    HANDLE  phIst = INVALID_HANDLE_VALUE;
    DWORD openStatus = IST_Open( _T("IST1:"), &phIst );

    if ( openStatus == IST_ERROR_SUCCESS ) {
        DWORD dropsD; IST_GetMotionEventLogCount(phIst, FREEFALL, &dropsD);
        int drops = (int)dropsD;
        if ( nRecords > drops ) nRecords = drops; if ( nRecords > 32 ) nRecords = 32;
        int pnRecords = 0; 
        IST_LOG_RECORD eventlog[32] = {0};

        DWORD getStatus = IST_GetMotionEventLogRecords(phIst, eventlog, drops, &pnRecords);

The last function gets a list of events and uses the given array to store that info. When the function returns the array is filled correcly, but the nRecords value is overwritten by '0'.

Does anyone know what i am doing wrong here?

Upvotes: 2

Views: 294

Answers (1)

valdo
valdo

Reputation: 12943

You have a memory overflow.

You adjust the variable nRecords so that it won't exceed 32, which is the maximum number of IST_LOG_RECORD that fit the eventlog array.

However you don't use it in the call to IST_GetMotionEventLogRecords. Instead you use drops, which equals to dropsD, which is not limited to 32.

Just use nRecords instead of drops:

DWORD getStatus = IST_GetMotionEventLogRecords(phIst, eventlog, nRecords, &pnRecords);

Upvotes: 3

Related Questions