正在重新分配的指针未分配

pointer being realloc'd was not allocated

size_t writeFunctionHandler(char *contents,size_t size,size_t nmemb,void *userdata) {
  // size of the storedSize
  static size_t storedSize = 0;

  // the size of data available
  size_t realSize = size * nmemb;

  char *dataBuffer = (char *) userdata;

  // realloc the buffer buffer
  dataBuffer = realloc(dataBuffer,storedSize + realSize);

  if (dataBuffer == NULL) {
    printf("Could not allocate memory \n");
    return 0;
  }

  // store the contents of realSize from last storedSize
  memcpy(&(dataBuffer[storedSize]),contents,realSize);

  storedSize += realSize;
  return realSize;
}

我不明白为什么上面的代码 return 和错误 正在重新分配的指针没有分配

当我使用这个示例代码时

struct MemoryStruct {
  char *memory;
};

size_t writeFunctionHandler(char *contents,size_t size,size_t nmemb, void *userdata) {
  size_t realSize = size * nmemb;
  static size_t storedSize = 0;
  //char *dataBuffer = (char *)userdata;
  struct MemoryStruct *chunk = (struct MemoryStruct *)userdata;

  printf("print 1\n");
  chunk -> memory = realloc(chunk -> memory,storedSize + realSize);
  printf("print 2\n");

  if (chunk -> memory == NULL) {
    printf("Could not allocate memory\n");
    return 0;
  }

  memcpy(&(chunk -> memory[storedSize]),contents,realSize);
  storedSize += realSize;
  printf("print 3\n");

  return realSize;
}

似乎一切正常。

上面这个是curl writeFunctionHandler

int main() {
   char *buffer = calloc(1,1);
   // struct MemoryStruct chunk;
   // chunk.memory = calloc(1,1);

   CURL *curl = curl_easy_init();

   curl_easy_setopt(curl, CURLOPT_URL, "http://whosebug.com");
   curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeFunctionHandler);
   curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)buffer);
   // curl_easy_setopt(curl,CURLOPT_WRITEDATA, (void *) &chunk);

   free(buffer);
   //free(chunk.memory);
   curl_easy_cleanup(curl);

   return 0;
}

除了我在后一种情况下使用 struct 之外,我无法理解这两个代码之间的区别。

重点是 userdata 指向包含成员 memory 的结构,它是从堆中分配的成员。

此外,当函数 returns 时,memory 可能已被 realloc 更改,但在您的版本中,函数外部无法看到更改。那是因为传递的是指针的,而不是地址。如果传递了地址(即 void **userdata),您将重新分配到该地址(即 *userdata= realloc(..)并且它会在函数外部可见。