很抱歉,如果我没有正确地表达问题,但在以下代码中:
int main() {
char* a=new char[5];
a="2222";
a[7]='f'; //Error thrown here
cout<<a;
}
如果我们试图访问程序中的 a[7],我们会得到一个错误,因为我们还没有被分配 a[7]。
但是如果我在类里面做同样的事情:
class str
{
public:
char* a;
str(char *s) {
a=new char[5];
strcpy(a,s);
}
};
int main()
{
str s("ssss");
s.a[4]='f';s.a[5]='f';s.a[6]='f';s.a[7]='f';
cout<<s.a<<endl;
return 0;
}
代码有效,打印字符“abcdfff”。 当我们只将 char[5] 分配给我们在第一个程序中无法这样做的一段时间时,我们如何能够访问代码中的 a[7] 等?
最佳答案
在你的第一种情况下,你有一个错误:
int main()
{
char* a=new char[5]; // declare a dynamic char array of size 5
a="2222"; // assign the pointer to a string literal "2222" - MEMORY LEAK HERE
a[7]='f'; // accessing array out of bounds!
// ...
}
你正在制造内存泄漏,然后询问为什么未定义的行为是未定义的。
你的第二个例子再次询问,为什么未定义的行为是未定义的。
关于c++ - 为什么我们能够访问类中未分配的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18901598/