c++ - 两次删除对象并导致内存错误
问题描述
我正在使用 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 两次?因为我每次都重新声明一个新对象。
解决方案
推荐阅读
- sqlite - sqlite attach database 命令的默认文件位置
- angular - bootstrap5 无法将 undefined 或 null 转换为对象
- json - 在 Azure Synapse 中以 JSON 格式返回 SQL 查询结果
- freeipa - 如果丢失了第一个主服务器,如何在 freeIPA 中提升复制的主服务器?
- woocommerce - 如何从 Woocommerce 中的产品描述内容中去除 HTML?
- dicom - 了解 DICOM 应用程序级机密性配置文件和选项
- node.js - Laravel - “Npm run hot”不起作用并给我这个错误
- node.js - MERN-Stack 电子商务网站的时事通讯功能
- amazon-web-services - Parquet 文件无效:AWS Glue 目录表不适用于 Snappy 文件
- android - Could not find aaptcompiler-4.2.0.jar