libcurl curl_easy_perform() 在函数内部移动时程序崩溃

libcurl curl_easy_perform() crashes program when moved inside function

使用带有 libcurl 库的 Qt5,我尝试从本地 FTP 服务器下载目录列表。如果我将所有 curl_easy_setopt() 和 curl_easy_perform() 保留在 main() 中,它将完美运行。但是,如果我尝试将它们全部放在一个函数中进行一次调用,程序会在到达 curl_easy_perform().

时崩溃

我使用的是 libcurl 版本 7.40.0 - Win32 Generic 2000/XP

#include "mainwindow.h"
#include <QApplication>
#include <curl/curl.h>
#include <QDebug>
#include <QFile>

struct FtpFile {
  const char *filename;
  FILE *stream;
};

size_t my_fwrite(void *buffer, size_t size, size_t nmemb, void *stream)
{
  struct FtpFile *out=(struct FtpFile *)stream;
  if(out && !out->stream) {
    /* open file for writing */
    out->stream=fopen(out->filename, "wb");
    if(!out->stream)
      return -1; /* failure, can't open file to write */
  }
  return fwrite(buffer, size, nmemb, out->stream);
}

int DownloadToFile(CURL *curl, FtpFile *file, bool ClearAfterWrite)
{
    qDebug() << "Before URL set";
    curl_easy_setopt(curl, CURLOPT_URL, "ftp://127.0.0.1");
    qDebug() << "URL set";

    curl_easy_setopt(curl, CURLOPT_USERPWD, "maptester:sync");
    qDebug() << "Login set";

    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_fwrite);
    qDebug() << "Write Function set";

    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&file);
    qDebug() << "Write Data set";

    int Result = curl_easy_perform(curl);
    qDebug() << "curl perform passed";

    if(ClearAfterWrite)
    {
        file->stream = NULL;
    }

    return Result;
}


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();


    FtpFile ftpfile =
    {
      "C:\users\Ir77\Desktop\ftpLS.txt", /* name to store the file as if succesful */
      NULL
    };

    curl_global_init(CURL_GLOBAL_DEFAULT);

    CURL *curl = curl_easy_init();
    qDebug() << "easy init passed";
    if(curl)
    {
        int Result;
        qDebug() << "curl check passed";
#if 1
        Result = DownloadToFile(curl, &ftpfile, true);
#else
        curl_easy_setopt(curl, CURLOPT_URL, "ftp://127.0.0.1/");

        curl_easy_setopt(curl, CURLOPT_USERPWD, "maptester:sync");

        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_fwrite);

        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&ftpfile);

        Result = curl_easy_perform(curl);

#endif

      if(Result != CURLE_OK)
      {
          qDebug() << "File Download error!";
      }
      else
      {
          qDebug() << "File got something!";
      }

      /* always cleanup */
      curl_easy_cleanup(curl);
    }

    curl_global_cleanup();


    return a.exec();
}

file里面的DownloadToFile已经是指向ftpfile结构的指针,所以去掉file变量前的&

curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)file);