我試圖得到段錯誤,但我無法得到它,我想知道爲什麼。C++試圖失敗構造函數
#include <iostream>
using namespace std;
class A{
public:
char *field_;
A(char *field):field_(field) {
// I believe(suppose) that it's equal to
// field_ = field;
// so actual initial string wasn't copied, only a pointer to it
}
void show() {
cout<<field_<<"\n";
}
};
int main(){
A *obj;
{
char *line="I should be freed";
obj = new (nothrow) A(line);
}
// After exiting from the previous scope,
// char *line variable should be freed.
// Constructor of class A didn't make byte for byte
//copying, so we cannot have
// access to it for sure
for(int i=0;i<4;i++) // trying to clear stack and erase char *line variable
char something[10000];
obj->show(); // and it works correctly!!!! why?
delete obj;
return 0;
}
好的,據我所知,它只是因爲該字符串沒有從內存中釋放正常工作。 也就是說我們只是幸運。 而這裏我們有未定義的行爲。我對嗎?
預先感謝您!
爲什麼要向堆棧中添加*東西來清除堆棧中已經存在的東西? (不是字符串本身在堆棧中) – Andrei 2013-05-10 21:30:04
如果字符串已經被分配到堆棧中,並且我們超出了範圍,所使用的內存被標記爲不必要,所以如果我們要求新的內存有一些概率,必要的內存將被使用,並且舊的字符串將被擦除(當然,不能保證完全取出內存)。例如。它並不適用於我的情況,即使在我將其定義爲char line [80] =「我應該被釋放」的情況下,在堆棧中,因爲該內存不僅僅是被佔用的。但有時它可以被覆蓋,有時不可以。糾正我,如果我錯了 – Tebe 2013-05-10 21:33:05
是的,錯過了標記範圍的榮譽... – Andrei 2013-05-10 21:41:40