realloc():下一个大小无效

Kew*_*ley 2 c libcurl realloc

我遇到了realloc函数的问题.我只使用C(因此没有向量)与LibCurl.我遇到的问题是我在write_data函数的第12次迭代中得到以下错误(realloc():无效的下一个大小)(我将函数作为回调传递给Curl,每次libcurl都调用它时一些要传回的数据(数据以块的形式传递)).

跟踪:

-Removed-

资源:

#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;
}
Run Code Online (Sandbox Code Playgroud)

提前致谢,

caf*_*caf 10

传入的数据write_data()不一定是空终止的; 这就是它告诉你字节数的原因.

这意味着你无法使用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.
}
Run Code Online (Sandbox Code Playgroud)

您还需要初始化RunningSize为0,而不是1.您可以初始化DataNULL- 允许传递NULLrealloc()(并使其行为就像malloc()).