(c++)调用一个curl方法两次,给出并出错

(c++) Call a curl method twice gives and error

本文关键字:两次 出错 方法 调用 c++ curl 一个      更新时间:2023-10-16

我正在开发一个Web服务,在c++中遇到了一个关于curl的小问题。以下代码

string WSUser::getUser(int id){
CURL *curl;
CURLcode res;
if(curl == NULL) curl = curl_easy_init();
if(curl) {
    ostringstream oss;
    curl_easy_setopt(curl, CURLOPT_URL, http://"example.com"); 
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
    res = curl_easy_perform(curl);
    curl_easy_cleanup(curl);
    if(res != CURLE_OK) return curl_easy_strerror(res);
}

工作正常,但问题是,当我再次调用这个方法时

WSUser *wsUser = new WSUser();
cout << wsUser->getUser(1) << endl;
cout << wsUser->getUser(2) << endl;

然后我得到一个错误:

在WebService.exe:0xC0000005:Zugriffsverletzung beim Lesen an Position 0xfeeefee8中取消绑定Ausnahme bei 0x54ba7e2c(msvcr100d.dll(。

此处为

CURL *curl;
CURLcode res;
if(curl == NULL) curl = curl_easy_init();

由于您没有初始化curl,它有一个不确定的值,并且使用它(即将它与NULL进行比较(是未定义的
在实践中最有可能发生的情况是,您或多或少会随机调用curl_easy_init,在curl中留下一个随机值。你只是运气不好,第一次打电话时正好有一个零,当时它没有崩溃。

你想要

CURL* curl = curl_easy_init();