memset时访问冲突错误

时间:2017-03-20 11:51:53

标签: c++11 pointers access-violation

 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的大小,那么它运作良好(我随机减小了一个数字的大小)。
  • 这是一个在64位Win OS 16GB RAM上运行的32位应用程序

我请求一些人帮助我理解失败的原因以及calloc-size-memset之间的关系。

1 个答案:

答案 0 :(得分:1)

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。