[英]c++: memory not freed by free()
我正在使用libcurl並從我的http服務器復制內容。 我需要獲取這些段並將獲取的段保存在新文件中。
正確提取了第一個段,但是第二個段將第一個段的內容附加到了該段,但不應添加。
在將第一段復制到我的文件后,應該釋放內存,但是不會發生。
部分代碼附后:
//code
char *m_pBuffer = NULL;
size_t m_Size = 0;
void* Realloc(void* ptr, size_t size)
{
if(ptr)
return realloc(ptr, size);
else
return malloc(size);
};
// Callback must be declared static, otherwise it won't link...
size_t WriteMemoryCallback(char* ptr, size_t size, size_t nmemb)
{
// Calculate the real size of the incoming buffer
size_t realsize = size * nmemb;
// (Re)Allocate memory for the buffer
m_pBuffer = (char*) realloc(m_pBuffer, m_Size + realsize);
// Test if Buffer is initialized correctly & copy memory
if (m_pBuffer == NULL) {
realsize = 0;
}
memcpy(&(m_pBuffer[m_Size]), ptr, realsize);
m_Size += realsize;
// return the real size of the buffer...
return realsize;
};
namespace ahs
{
/* Construction / Initialisation */
{
return 0;
}
{
curlpp::Cleanup cleaner;
curlpp::Easy request;
// Set the writer callback to enable cURL
// to write result in a memory area
curlpp::types::WriteFunctionFunctor functor(WriteMemoryCallback);
curlpp::options::WriteFunction *test = new curlpp::options::WriteFunction(functor);
request.setOpt(test);
// Setting the URL to retrive.
string abc = "http://192.168.0.34/ahs-1.0/example/ingest";
string kk= abc + tobeused;
request.setOpt(new curlpp::options::Url(kk));
request.setOpt(new curlpp::options::Verbose(true));
request.perform();
print();
}
catch ( curlpp::LogicError & e )
{
std::cout << e.what() << std::endl;
}
catch ( curlpp::RuntimeError & e )
{
std::cout << e.what() << std::endl;
}
FILE *fp;
if((fp = fopen(pp, "wb")) == NULL) {
printf("Cannot open file.\n");
exit(1);
}
if( fwrite(m_pBuffer, (long)m_Size, 1, fp) != 1) {
printf("Write Error.\n");
exit(1);
}
fclose(fp);
free(m_pBuffer);
首先,您正在使用C ++。 使用std::vector
處理您的緩沖區,然后這個問題就消失了。
其次,你有一個調用的函數Realloc
而是要求realloc
,這是故意的嗎?
這是一個非常危險的電話:
// (Re)Allocate memory for the buffer
m_pBuffer = (char*) realloc(m_pBuffer, m_Size + realsize);
如果realloc返回NULL,則最初由m_pBuffer指向的數據將丟失:您沒有指向它的數據,您將無法再釋放它。
順便說一句,您可以使用帶有附加的std :: vector而不是進行重新分配,並且如果您不需要連續的緩沖區,可以使用帶有附加的std :: deque,這對於大型緩沖區特別有效,並且您可以當然,即使您正在寫一些空字節,也要使用std :: string。
重新分配您執行操作的方式的問題是,它將每次都進行重新分配並移動所有內存,並且最終會導致O(N ^ 2)。
您應該能夠獲得估計的大小。 順便說一句,如果您要做的只是將其寫入持久性中,您是否可以一次不做一個緩沖區,並且不先將其全部加載到內存中?
(我認為這可能是您正在嘗試做的事情,但不是)。
您在其中有一個memcpy
正在執行附加操作...
memcpy(&(m_pBuffer[m_Size]), ptr, realsize);
因此,您重新分配了緩沖區(擴展),但並沒有按預期的那樣清理緩沖區,而是將內容留在那里,然后將其放入重新分配的空間中,然后復制到新內容中……您感到驚訝嗎? 您是否從某處復制了代碼?
據我所知,您正在得到想要的東西。 您分配一些內存(第一個塊的大小),並用第一個塊填充它。
然后,您將該內存的大小增加到第一個和第二個塊的大小,並在第一個塊之后立即填充第二個塊,以便您的內存中包含第一個和第二個塊。
如果最后一次寫出此內存,這很好。 如果在每個塊之后將其寫出,則需要記住您在內存塊中的位置,或者只是為每個塊分配內存,將其填充,寫出然后釋放它。
您只需要輸入m_Size=0;
在每個獲取的段之后。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.