gpt4 book ai didi

c - realloc() : invalid next size

转载 作者:行者123 更新时间:2023-12-01 23:15:01 25 4
gpt4 key购买 nike

我的 realloc 函数有问题。我只使用 C(所以没有 vector )和 LibCurl。我遇到的问题是我在 write_data 函数的第 12 次迭代中收到以下错误(realloc(): invalid next size)(我作为回调传递给 Curl 的函数,每次 libcurl 都有一些要传回的数据(数据以 block 的形式传递)。

跟踪:

-删除-

来源:

#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
#include <string.h>

char * Data; //stores the data
size_t RunningSize;

int write_data( char *ptr, size_t size, size_t nmemb, void *stream )
{
size_t ThisSize = (size * nmemb); //Stores the size of the data to be stored
size_t DataLen = strlen( Data ); //length of the data so far

RunningSize = (RunningSize + ThisSize ); //update running size (used as new size)

Data = realloc( Data, RunningSize ); //get new mem location (on the 12th iteration, this fails)
strcat( Data, ptr); //add data in ptr to Data

return ThisSize; //the function must return the size of the data it received so cURL knows things went ok.
}

int main( )
{
CURL *curl;
CURLcode res;
const char * UserAgent = "";

Data = malloc(1); //so realloc will work
RunningSize += 1;

curl = curl_easy_init();
if(curl)
{
curl_easy_setopt( curl, CURLOPT_NOBODY, 0 );
curl_easy_setopt( curl, CURLOPT_URL, "http://www.google.co.uk/" );
curl_easy_setopt( curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt( curl, CURLOPT_USERAGENT, UserAgent );
curl_easy_setopt( curl, CURLOPT_HEADER, 1 );

//preform request.
res = curl_easy_perform(curl);

//output the data (debugging purposes)
puts( Data );

//cleanup
curl_easy_cleanup(curl);
free(Data);
}

return 0;
}

提前致谢,

最佳答案

传递给 write_data() 的数据不一定是 nul 终止的;这就是它告诉你字节数的原因。

这意味着你不能使用 strcat()。使用它会超出数组的末尾并破坏 malloc/realloc 使用的数据结构,因此会出现错误。

你的 write_data() 应该使用 memcpy() 代替,像这样:

int write_data( char *ptr, size_t size, size_t nmemb, void *stream )
{
size_t ThisSize = (size * nmemb); //Stores the size of the data to be stored
size_t DataLen = RunningSize; //length of the data so far

RunningSize = (RunningSize + ThisSize ); //update running size (used as new size)

Data = realloc( Data, RunningSize ); //get new mem location (on the 12th iteration, this fails)
memcpy((char *)Data + DataLen, ptr, ThisSize); //add data in ptr to Data

return ThisSize; //the function must return the size of the data it received so cURL knows things went ok.
}

您还需要将 RunningSize 初始化为 0,而不是 1。您可以将 Data 初始化为 NULL - 传递 NULLrealloc() 是允许的(并使其行为类似于 malloc())。

关于c - realloc() : invalid next size,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2939091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com