【发布时间】:2014-04-27 02:03:15
【问题描述】:
我在尝试删除指针(对于 char 数组)时遇到段错误。请帮我。我在这里做错什么了吗。请在下面找到代码 sn-p 和输出。
代码:
# include <iostream>
using namespace std;
int main()
{
int *p = new int;
const char* c = new char[100];
c = " hello";
*p = 10;
cout << "c= " << c << "*p = " << *p << endl;
delete p;
delete c;
c = NULL;
p = NULL;
return 0;
}
输出:
c= hello*p = 10
Segmentation fault (core dumped)
编辑:
如果我不对字符数组使用 new 和 delete,会不会是内存泄漏?我不能在我的代码中使用字符串,那么使用 const char* 变量的正确方法是什么?
提前致谢。
【问题讨论】:
-
在使用 C++ 编程时,您应该阅读并学习使用 standard library,它将对您有很大帮助。例如,不要对字符串使用指针,而应使用
std::string。
标签: c++ linux pointers char constants