[問題] 請問關於字串的 memory leak 問題

看板C_and_CPP (C/C++)作者 (小乖)時間16年前 (2009/06/05 11:05), 編輯推噓3(306)
留言9則, 3人參與, 最新討論串1/1
================================================ #include <iostream> #include <string> using namespace std; string* str = new string("I am big"); int main() { cout << "string memory leak" << endl; str = new string("Actually, I am small"); return 0; } ================================================= 在上述程式中, "I am big" 這個string物件將會沒有指標指到, 造成 memory leak。 解決方法是用 delete 釋放 string 物件 int main() { delete str; str = new string("Actually, I am small"); return 0; } 這是使用 std::string 的方式 我後來想到,若是用 C 語言的字串陣列方式 那要怎麼 delete ?? =================================================== char* a = "I am big"; int main() { a = "Actually, I am small"; return 0; } ==================================================== 在此段敘述中, "I am big" 沒有被指到 我用 visual studio 2005 跑的結果,有兩個問題? 1. debug mode 中沒有顯示有發生 memory leak 情況 2. 似乎沒有辦法用 delete 去將 "I am big" 物件清空? 請問是什麼原因讓debuger會說沒有 memory leak 情況發生 以及若是我想清除 "I am big" 要如何清除?? Note: 我猜想 compiler 可能會產生 string table 存放 "I am big" 不過其運作機制就不是很了解,這樣我要清除 "I am big" 也無法清除了。 若是 Java or C# 似乎不必考慮這麼多 XD -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.132.97.179

06/05 11:32, , 1F
i am big 和 a i am small 是不能被delete的
06/05 11:32, 1F

06/05 11:32, , 2F
char *p="test1"; 這是指p指到一個const char string,
06/05 11:32, 2F

06/05 11:33, , 3F
這空間本來就不是dynamic alloc的, 所以也沒有讓你free
06/05 11:33, 3F

06/05 11:33, , 4F
的問題, 事實上它不在heap, 你去free反而會有問題@_@"
06/05 11:33, 4F

06/05 11:36, , 5F
只是我不確定text1或者之後p另外assign到其他const char
06/05 11:36, 5F

06/05 11:36, , 6F
string後, 這些TEXT memory怎麼算, 如果很在乎的話, 就
06/05 11:36, 6F

06/05 11:36, , 7F
用malloc+strcpy來做這些assign/copy的動作吧@_@"
06/05 11:36, 7F

06/05 11:38, , 8F
如果是"xx"之類的,大概都是存在data segment吧!
06/05 11:38, 8F

06/05 12:19, , 9F
literal pool??
06/05 12:19, 9F
文章代碼(AID): #1AA8k28d (C_and_CPP)
文章代碼(AID): #1AA8k28d (C_and_CPP)