使用字符串内存

时间:2014-04-25 17:04:00

标签: c++ string visual-c++

为什么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);
}

2 个答案:

答案 0 :(得分:4)

你只分配一个角色;然后你写它和它后面的两个字节的内存,给出未定义的行为。

如果你想分配一个包含十个字符的数组,那就是

char *pcResult = new char[10];

并且需要作为数组删除

delete [] pcResult;

但是,除非这是学习低级记忆诡计的练习,否则请使用std::string来表示字符串。

答案 1 :(得分:0)

你可能意味着:

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