2015-10-11 71 views
1

在我的一個C++函數中,我打電話給ab demangle。我想在將其更改爲字符串之後解除分配結果。下面是代碼:在C++中使用free(const char *)11

const char * realName; 
string name; 
const std::type_info &ti = typeid(*this); 
realName = abi::__cxa_demangle(ti.name(), 0, 0, &status); 

name= realName; 
int index =name.find_last_of(':'); 
name = name.substr(index+1, name.length()-index-1); 
free((void *) realName); 

的代碼運行沒有問題,但是Eclipse編譯器是不是快樂,展示了使用免費的錯誤:「功能‘免費’無法解析」。

我試圖用刪除的,而不是免費的。

delete realName; 

的代碼運行沒有問題,和eclipse編譯器是幸福的,但是當我用Valgrind的配置代碼,我得到一個剖析錯誤: 不匹配的free()/刪除/刪除[]

所以我的問題是: 1 - 我應該在C使用免費++或應我使用時只需刪除,刪除[] 2 - 如果我不應該免費使用的valgrind爲什麼給我一個錯誤 3-如果我應該使用免費的爲什麼Eclipse CDT的comipler給我一個編譯錯誤,但是當我運行代碼時,一切正常。 4-是我的代碼有正確的風格基於c + + 11?或者它是C和舊C++的組合?

回答

6

Should I use free in C++ or shall I use just delete , delete[] ?

你應該使用功能或配置相匹配的運營商。當你分配內存供自己使用時,你應該使用new/new[]進行分配,並使用delete/delete[]進行重新分配。

當要釋放的內存來自其他源(如__cxa_demangle)時,您應該閱讀文檔以瞭解需要在釋放時使用哪些功能。該documentation您函數的規定,

the demangled name is placed in a region of memory allocated with malloc .

因此,您必須使用free釋放它。

If I should use free why Eclipse cdt compiler is giving me a compile error but when I am running code everything is OK.

功能free<cstdlib>頭中定義。您需要將此標題添加到您的cpp文件,以確保您的代碼編譯正常。

+0

感謝您的回答。我應該使用還是?爲什麼代碼在eclipse中運行時沒有問題,但是它在eclipse中顯示編譯錯誤? – Govan

+0

@Govan在C++''頭對應於''的C. – dasblinkenlight

+0

''保證'std :: free'存在,''保證'free'存在(在全局命名空間中),它不能保證反過來工作 –

2

你必須使用free的文件說,使用free

也許你需要包含正確的頭文件和庫。 #include <stdlib.h>也許-lC