内存设置时访问冲突错误


 typedef struct
 {
   long nIndex;                     // object index
   TCHAR    path[3 * MAX_TEXT_FIELD_SIZE];
  }structItems;
void method1(LPCTSTR pInput, LPTSTR pOutput, size_t iSizeOfOutput)
{
  size_t        iLength = 0;
  iLength = _tcslen(pInput);
  if (iLength > iSizeOfOutput + sizeof(TCHAR))
    iLength = iSizeOfOutput - sizeof(TCHAR);
  memset(pOutput, 0, iSizeOfOutput); // Access violation error
}
void main() 
{
   CString csSysPath = _T("fghjjjjjjjjjjjjjjjj");
   structItems *pIndexSyspath = nullptr;
   pIndexSyspath = (structItems *)calloc(1, sizeof(structItems) * 15555555); //If i put size as 1555555 then it works well
   method1(csSysPath, pIndexSyspath[0].path, (sizeof(TCHAR) * (3 *     MAX_TEXT_FIELD_SIZE)));
}

这是导致崩溃的示例代码。

  • 在上面的代码中,如果我们放置的大小1555555那么它运行良好(我随机将大小减小了一个数字(。
  • 这是一个 32 位应用程序,在 64GB RAM 上的 16 位 Win OS 上运行

我恳请有人帮助我了解失败的原因以及 calloc - size - memset 之间的关系。

typedef struct
{
    long nIndex;  // 4 bytes on Windows
    TCHAR    path[3 * MAX_TEXT_FIELD_SIZE]; // 1 * 3 * 255 bytes for non-unicode
} structItems;

假设非 unicode,TCHAR是 1 字节,MAX_TEXT_FIELD_SIZE是 255,所以sizeof(structItems)255*3 + 4,对于结构来说,这是 769 个字节。现在,您要分配sizeof(structItems) * 15555555,它大于 11GiB。这如何适合 32 位进程可用的 2GiB。

相关内容

最新更新