首页 > 解决方案 > 两次删除对象并导致内存错误

问题描述

我正在使用 C++ lubcurl 库。基本上,我想将 curl 用于来自 Web 服务器的 GET 和 POST 请求。在这种特殊情况下,我使用 GET 请求来检索必要的消息,并通过等待带有 _id 字段的任何新数据向服务器发送垃圾邮件,如下所示(我已删除与此错误无关的不必要代码)。我遇到的错误是内存的双重释放。我的代码是:

#include "ros/ros.h"
#include "geometry_msgs/PoseStamped.h"
#include <boost/asio.hpp>
#include <iostream>
#include <cstdint>
#include <memory>
#include <string>
#include <math.h>
#include <tf2/LinearMath/Quaternion.h>

#include <curl/curl.h>
#include <jsoncpp/json/json.h>

std::size_t callback(const char* in, std::size_t size, std::size_t num, std::string* out){
    const std::size_t totalBytes(size* num);
    out->append(in, totalBytes);
    return totalBytes;
}


int main(int argc, char **argv){

    ros::init(argc, argv, "api_handler");
    ros::NodeHandle nh;
    ros::Publisher pub = nh.advertise<geometry_msgs::PoseStamped> ("/move_base_simple/goal", 1000);
    ros::Rate loop_rate(10);
    /*boost::asio::ip::tcp::iostream stream;
    stream.connect("jsonplaceholder.typicode.com", "http");*/
    const std::string main_url("https://wheelme-protocol-bridge.herokuapp.com/goal/");
    ///
    tf2::Quaternion q;
    int _id = 1;



    while(ros::ok()){
        geometry_msgs::PoseStamped msg;
        std::string url = main_url + std::to_string(_id);
        CURL* curl = curl_easy_init();
        // remote url
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        // Using ipv4
        curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        // waiting time of 10 sec
        curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10);
        // HTTP redirects if necessary
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);

        //response info
        long httpCode(0);
        std::unique_ptr<std::string> httpData(new std::string());

        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback);

        // Hook up a container type for CURL:
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, httpData.get());

        // Cleaning the HTTP and catching the response:
        curl_easy_perform(curl);
        curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);
        curl_easy_cleanup(curl);
        if (httpCode=200){
            ROS_INFO("Got successful response");
            Json::Value jsonData;
            Json::Reader jsonReader;
            if (jsonReader.parse(*httpData.get(), jsonData)){
                ROS_INFO("Parsed JSON data");
                const double x(jsonData["position"]["x"].asDouble());
                    // Doing some stuf with JSON data

            }
            else{
                ROS_INFO("Could not parse json response");
            }
        }
        else{
            ROS_INFO("No new goal");
        }


        ros::spinOnce();
        loop_rate.sleep();
    }

    return 0;

}

我在这里使用 ROS,但这也无关紧要,因为这里的问题是我对 libcurl 的错误使用。然而,重要的是 while(ros::ok()),它是一个无限循环,会一次又一次地运行,直到主机启动。所以我明白问题是我对 lubcurl 对象 curl 的双重删除(免费),但我不明白我在哪里释放 curl 两次?因为我每次都重新声明一个新对象。

标签: c++libcurl

解决方案


推荐阅读