指针是realloc&d;未被分配

时间:2017-03-26 06:17:10

标签: c realloc

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;
}

我无法理解为什么上面的代码返回并且错误指针被重新分配&#d; d未分配

当我使用此示例代码时

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;
}

一切似乎都运转正常。

以上是卷曲 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://stackoverflow.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;
}

我无法理解2代码之间的区别,除了我在后面的情况下使用struct的事实。

1 个答案:

答案 0 :(得分:3)

关键是userdata指向包含成员memory的struct,它是从堆中分配的成员。

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