作者spider391 (小乖)
看板C_and_CPP
標題[問題] 請問關於字串的 memory leak 問題
時間Fri Jun 5 11:05:37 2009
================================================
#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
1F:→ ilway25:i am big 和 a i am small 是不能被delete的 06/05 11:32
2F:推 VictorTom:char *p="test1"; 這是指p指到一個const char string, 06/05 11:32
3F:→ VictorTom:這空間本來就不是dynamic alloc的, 所以也沒有讓你free 06/05 11:33
4F:→ VictorTom:的問題, 事實上它不在heap, 你去free反而會有問題@_@" 06/05 11:33
5F:推 VictorTom:只是我不確定text1或者之後p另外assign到其他const char 06/05 11:36
6F:→ VictorTom:string後, 這些TEXT memory怎麼算, 如果很在乎的話, 就 06/05 11:36
7F:→ VictorTom:用malloc+strcpy來做這些assign/copy的動作吧@_@" 06/05 11:36
8F:→ ilway25:如果是"xx"之類的,大概都是存在data segment吧! 06/05 11:38
9F:推 stonehomelaa:literal pool?? 06/05 12:19