为什么我们不能删除已初始化的指针? [英] Why can't we delete an initialized pointer?
本文介绍了为什么我们不能删除已初始化的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我用一些随机值初始化一个 char
指针,当我试图删除它时,我无法。为什么呢?
I am initializing a char
pointer with some random values, and when I am trying to delete it, I am unable to. Why is that?
这里是我在做什么:
int main()
{
char *s = new char[50]; // I know there is no reason for using new if initializing, but in order to use delete we need to allocate using new.
s = "Harry";
delete s;
return 0;
}
推荐答案
如果你真的想练习用指针,你需要修复你的代码。主要的问题是你试图分配字符串文字(这是 const char [6] 在这里)指针 s
然后尝试修改它通过调用delete调用未定义的行为( UB
)。
If you really want to practice with pointer, you need to fix your code. The main problem is you are trying to assign string literal( which is const char[6] in here) to pointer s
then try to modify it by calling delete which invoke undefined behavior(UB
).
char *s = new char[50];
strcpy(s, "Harry"); // don't assign string literal to it
// re-assign pointer to string literal,
// lost pre-allocated memory position and caused delete to fail
// it's UB to modify string literal
delete []s; // new[]/delete[], new/delete need to be called in pair.
只需使用 std :: string
#include <string>
std::string s("Harry"); // no worries
这篇关于为什么我们不能删除已初始化的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文