使用字符串内存
Working with string memory
为什么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;
}
相关文章:
- 将字符串存储在c++中的稳定内存中
- 为什么字符串的 move() 会改变内存中底层数据的位置?
- 当分配一个字符串值并稍后通过分配另一个值进行更改时C++如何管理内存?
- 字符串共享内存映射的向量
- C++将字符串传递给 C 库以进行内存管理
- 内存增加和字符串流?
- 如何从内存中读取字符串?
- 自定义哈希表实现-将字符串映射到整数时出现内存错误
- 交换两个字符串时访问正确的内存时,我遇到了分段错误
- 通过 mmap-ed 共享内存传递可变长度 C 字符串
- 字符串的内存高效向量
- 为什么cout输出内存地址不是字符串?
- 如何使用 RPM 从内存中读取标准::字符串
- 在带有 (void*) 强制转换的字符串中打印字符的内存地址
- Visual C 运行时:Malloc将指针返回到已经使用的内存(包含实际字符串)
- 字符串标记化期间的内存损坏
- 如果我不将预先编写的字符串保存到变量,它还在内存中吗?
- 放置在外部 DLL 中的类中的字符串数据的内存损坏
- 删除字符串指针在struct中的内存
- 字符串编码用于内存优化