2011-05-23 76 views
2

我想分配內存的結構數組,但分配後,在函數中傳遞的int被設置爲'0'...問題沒有了,當時我增加了數組的大小。這裏是我的代碼:內存覆蓋後分配的結構數組

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); 

最後一個函數獲取事件列表並使用給定的數組來存儲該信息。當函數返回時,數組被正確填充,但nRecords值被'0'覆蓋。

有人知道我在這裏做錯了嗎?

回答

3

您有內存溢出。

您調整變量nRecords,使其不超過32,這是適合eventlog陣列的最大數量IST_LOG_RECORD

但是,您不要在撥打IST_GetMotionEventLogRecords的電話中使用它。而是使用drops,相當於dropsD,這是限制爲32

只需使用nRecords代替drops

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

這就是它!謝謝你,我搞砸了......謝謝 – 2011-05-23 14:35:13