使用字符串内存

Working with string memory

本文关键字:内存 字符串      更新时间:2023-10-16

为什么delete(pcResult);会在下面的代码中出现异常?

void strange(char *pcResul)
{
    CString  pss ="123";
    strncpy (pcResul,(LPCTSTR)pss,3);
}
void Dlg::OnBnClickedUser()
{
char *pcResult = new char (10);
strange(pcResult);
delete(pcResult);
}

您只分配了一个字符;然后写入它,然后写入两个字节的内存,给出未定义的行为。

如果你想分配一个由十个字符组成的数组,那么这就是

char *pcResult = new char[10];

并且需要作为阵列删除

delete [] pcResult;

但是,除非这是一个学习低级内存恶作剧的练习,否则请使用std::string来表示字符串。

您的意思可能是:

void Dlg::OnBnClickedUser()
{
  char *pcResult = new char[10]; // Allocate an array of `char`, not char with value of 10.
  strange(pcResult);
  delete [] pcResult;
}