【问题标题】:Memory overwritten after allocating array of structs分配结构数组后覆盖的内存
【发布时间】:2011-05-23 13:59:32
【问题描述】:

我正在尝试为结构数组分配内存,但在分配内存后,函数中传递的 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”覆盖。

有谁知道我在这里做错了什么?

【问题讨论】:

    标签: c++ arrays memory-leaks memory-management


    【解决方案1】:

    你有内存溢出。

    您调整变量 nRecords 使其不超过 32,这是适合 eventlog 数组的 IST_LOG_RECORD 的最大数量。

    但是,您不会在调用 IST_GetMotionEventLogRecords 时使用它。相反,您使用 drops,它等于 dropsD,不限制为 32。

    只需使用nRecords 而不是drops:

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

    【讨论】:

      猜你喜欢
      • 2013-12-09
      • 2019-03-06
      • 2014-04-21
      • 2021-05-29
      • 2018-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多