Segmentation fault(core dumped) -ROS error - c++

Trying to write a cpp code to print out messages from camera image using darknet. I built a class in which there is mutex method which I use for utilizing callback message in multiple threads. Although catkin_make builds the file successfully, it gives segmentation error when I run the ros command with rosrun . The code is as follows:
#include "ros/ros.h"
#include "darknet_ros_msgs/BoundingBoxes.h"
#include "darknet_ros_msgs/BoundingBox.h"
#include<string>
#include<thread>
#include<iostream>
#include <mutex>
#include "geometry_msgs/Twist.h"
class Firstolo
{
private:
std::mutex yolo_mtx;
darknet_ros_msgs::BoundingBoxes last_yolo_msg;
public:
void callback(const darknet_ros_msgs::BoundingBoxes& msg)
{
std::lock_guard<std::mutex> lck(yolo_mtx);
last_yolo_msg = msg;
}
const darknet_ros_msgs::BoundingBoxes getYoloLastMsg()
{
std::lock_guard<std::mutex> lck(yolo_mtx);
return last_yolo_msg;
}
void dothejob()
{
std:: cout << "Here it goes: " << getYoloLastMsg().bounding_boxes[0].xmin << std::endl;
std:: cout << "Here it goes: " << getYoloLastMsg().bounding_boxes[0].xmax << std::endl;
std:: cout << "\033[2J\033[1;1H";
}
Firstolo()
{
}
Firstolo(Firstolo&)
{
std::mutex yolo_mtx;
}
~Firstolo()
{
}
};
int main( int argc, char **argv)
{
ros::init(argc,argv,"cood_subscriber");
Firstolo nc;
ros::NodeHandle nh;
ros::Subscriber sub;
sub = nh.subscribe("/darknet_ros/bounding_boxes", 100, &Firstolo::callback, &nc);
nc.dothejob();
ros::spin();
return 0;
}
Edit: It turns out that the problem is in the void dothejob(). I added std::lock_guardstd::mutex lck(yolo_mtx); to the void dothejob() and Segmentation error no longer shows up. Now the only remaining problem is that std:: cout << "Here it goes: " << getYoloLastMsg().bounding_boxes[0].xmin << std::endl; line keeps waiting for messages rather than printing them out. In fact, messages naturally should appear since there is darknet running in the background and generating messages.

Related

Parsing Pointers & Using them between classes [C++]

So I'm fairly new to C++ and I've only started to code into it a few weeks or so. I've been facing a problem that I could not manage to fix. Every time I learned a new programming language, I give myself the challenge to make a little program (not too complex) which groups everything I've learned about that language (functions, classes, arrays, pointers and so on) so I can get a good understand of how actually coding in that language is.
So I decided to make my first C++ program called Chek to check the current MBPS (connection speed) every hour, minutes, or second that the user can input. Like all of my programs, I use a structure that I always use that I discovered while coding in Java (Since I know Java fluidly). Which looks like this:
I've also added a comment of where my issue is in the whole in Lib/Arguments.cpp.
Let's say I was to code Chek in Java. I would do my structure like:
Chek or Main class
|- Core
|- Core (The class that handles initiating each core's libraries)
|- Arguments (For parsing, checking and understand arguments)
|- Broadcast (To print to screen and so on)
|- Network (For network interaction)
|- Logs (To save to file logs)
Then the rest ...
Each Core's lib is handled by the Core, like... To call the Broadcast methods, I would do:
Main().getCore().getBroadcast().BroadcastMsg("Hello!");
So I can access all libraries, methods, and variables without creating deadlocks or any infinite importing loops.
My problem is I'm trying to do this in C++ but it's not working! I've tried a lot of stuff, changing pointers to Object and so on but it doesn't work so I need help!
Here's my code (I'm also using Visual Studio):
Chek.cpp:
#include "pch.h"
#include "Main.h"
#include "Core.h"
#include <iostream>
int main(int argc, char *argv[])
{
Core* Ptr = new Core;
Main OBJ; Main* Ptr2; Ptr2 = &OBJ;
std::cout << "Generated PTR's!" << std::endl;
std::cout << "Core PTR -> " << Ptr << std::endl;
std::cout << "Main PTR -> " << Ptr2 << std::endl << std::endl;
Ptr2->SetCrPtr(Ptr);
Ptr2->loadChek(argv);
}
Main/Main.h:
#pragma once
#ifndef __MAIN_H
#define __MAIN_H
class Core;
class Main
{
public:
Main();
private:
Core* CrPtr;
public:
void loadChek(char *arguments[]);
void SetCrPtr(Core* Ptr);
Core* getCrPtr();
};
#endif
Main/Main.cpp:
#include "pch.h"
#include "Main.h"
#include "Core.h"
#include "Arguments.h"
#include "Broadcast.h"
#include <iostream>
using namespace std;
Main::Main() : CrPtr() {};
void Main::SetCrPtr(Core* Ptr)
{
std::cout << "[Main] Setting CrPtr to " << Ptr << std::endl;
this->CrPtr = Ptr;
}
Core* Main::getCrPtr()
{
return this->CrPtr;
}
void Main::loadChek(char *arguments[])
{
char *allArguments[sizeof(arguments)];
this->CrPtr->SetMnPtr(this);
this->CrPtr->setArguments();
this->CrPtr->setBroadcast();
this->CrPtr->getBroadcast()->Log(1, "Loading arguments ...\n");
this->CrPtr->getArguments()->parseArguments(arguments, allArguments);
}
Core/Core.h:
#pragma once
#ifndef __CLASS_H
#define __CLASS_H
#include "Arguments.h"
#include "Broadcast.h"
class Main;
class Core
{
public:
Core();
private:
Main* MnPtr;
Arguments* ArgPtr;
Broadcast* BrdPtr;
public:
Arguments* getArguments();
void setArguments();
Broadcast* getBroadcast();
void setBroadcast();
void SetMnPtr(Main* Ptr);
};
#endif
Core/Core.cpp:
#include "pch.h"
#include "Core.h"
#include "Main.h"
Core::Core() : MnPtr() {}
void Core::SetMnPtr(Main* Ptr)
{
std::cout << "[Core] Setting MnPtr to " << Ptr << std::endl;
this->MnPtr = Ptr;
}
void Core::setArguments()
{
this->ArgPtr = new Arguments;
std::cout << "[Core] Setting Argument's MnPtr to " << this->MnPtr << std::endl;
this->ArgPtr->SetMnPtr(this->MnPtr);
}
void Core::setBroadcast()
{
this->BrdPtr = new Broadcast;
std::cout << "[Core] Setting Broadcast's MnPtr to " << this->MnPtr << std::endl;
this->BrdPtr->SetMnPtr(this->MnPtr);
}
Arguments* Core::getArguments()
{
return ArgPtr;
}
Broadcast* Core::getBroadcast()
{
return BrdPtr;
}
Lib/Arguments.h:
#pragma once
class Main;
class Arguments
{
public:
Arguments();
private:
Main* MnPtr;
public:
void parseArguments(char *arguments[], char *argumentsElements[]);
void SetMnPtr(Main* Ptr);
Main* GetMnPtr();
};
Lib/Arguments.cpp:
#include "pch.h"
#include "Arguments.h"
#include <iostream>
Arguments::Arguments() : MnPtr() {}
void Arguments::SetMnPtr(Main* Ptr)
{
std::cout << "[Arguments] Setting MnPtr to " << Ptr << std::endl;
this->MnPtr = Ptr;
}
Main* Arguments::GetMnPtr()
{
return this->MnPtr;
}
void Arguments::parseArguments(char *arguments[], char *argumentsElements[])
{
try {
if (sizeof(arguments) == 1 || sizeof(arguments) > 4) throw 1;
}
catch (int errorCode) {
if (errorCode == 1) std::cout << "Wrong usage!\n\nUsage: chek.exe <timeout-in-miliseconds> <log-file-path>\nExample: chek.exe 10000 saturday_log_file.txt\n";
}
std::cout << "Size -> " << sizeof(arguments) << std::endl;
for(int i=0; i<sizeof(arguments); i++)
{
// The error is produced here, for some reason after MnPtr,
// nothing is recognised. Like getCrPtr()... has never been declared?
this->MnPtr->getCrPtr()->getBroadcast()->(1, "Works!");
}
}
Lib/Broadcast.h:
#pragma once
#include <iostream>
#include "Main.h"
class Broadcast
{
public:
Broadcast();
private:
Main* MnPtr;
public:
void Log(unsigned int statusLevel, std::string message);
void SetMnPtr(Main* Ptr);
};
Lib/Broadcast.cpp:
#include "pch.h"
#include "Broadcast.h"
#include <iostream>
#include <string>
using namespace std;
Broadcast::Broadcast() : MnPtr() {}
void Broadcast::SetMnPtr(Main* Ptr)
{
std::cout << "[Broadcast] Setting MnPtr to " << Ptr << std::endl;
this->MnPtr = Ptr;
}
void Broadcast::Log(unsigned int statusLevel, string message)
{
switch (statusLevel) {
case 1:
cout << "[.] " << message;
break;
case 2:
cout << "[+] " << message;
break;
case 3:
cout << "[!] " << message;
break;
case 4:
cout << "[X] " << message;
break;
}
}
Errors:
I get 3 errors.
Visual Studio Error (When you hover it):
Arguments *const this
Pointers to incomplete class is not allowed.
From the error box (Visual Studio):
Error C2027 use of undefined type 'Main' Chek2 c:\users\xxx\documents\programming\c++\vs workspace\chek2\arguments.cpp 30
Error (active) E0393 pointer to incomplete class type is not allowed Chek2 C:\Users\xxx\Documents\Programming\C++\VS Workspace\Chek2\Arguments.cpp 30
Compiler Errors:
1>c:\users\xxx\documents\programming\c++\vs workspace\chek2\arguments.cpp(30): error C2027: use of undefined type 'Main'
1>c:\users\xxx\documents\programming\c++\vs workspace\chek2\arguments.h(3): note: see declaration of 'Main'
If anyone could help me with this. I would highly appreciate it! I hope it's not too hard of a problem- fairly new to C++ so I don't know exactly what this is compared to Java.
Thanks to #drescherjm for answering in comments. I just needed to add:
#include "Main.h"
#include "Core.h"
Inside Arguments.cpp's includes!

C++ Boost multithreading inside a class

I am following Boost multithreading tutorial here
. Following section 18.13, I try creating a class containing multiple threads as follows:
#define _CRT_SECURE_NO_WARNINGS
#include <ctime>
#include <iostream>
#include <string>
#include <queue>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/thread.hpp>
#include <boost/thread/thread.hpp>
#include <boost/chrono.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using boost::asio::ip::udp;
using std::cout;
using std::cin;
using std::endl;
using std::string;
using namespace std;
class MultiTask
{
private:
boost::thread_group threads; // thread group
boost::thread* thread_main; // main thread
boost::thread* thread_output; // output thread
boost::thread* thread_input; // input thread
boost::mutex stopMutex;
bool stop;
int i_in, i_out, i_main;
string userInput;
public:
// constructor
MultiTask()
{
thread_main = new boost::thread(boost::ref(*this));
thread_output = new boost::thread(&MultiTask::Callable_Out, this, 1000, boost::ref(i_out));
thread_input = new boost::thread(&MultiTask::Callable_In, this, 1000, boost::ref(i_out), boost::ref(userInput));
//threads.add_thread(thread_main); // main thread = 0 // will throw -> boost thread: trying to join itself
threads.add_thread(thread_output); // output thread = 1
threads.add_thread(thread_input); // input thread = 2
stop = false;
i_in = 0;
i_out = 0;
i_main = 0;
userInput = "";
}
// destructor
~MultiTask()
{
// stop all threads
Stop();
// show exit message
cout << "Exiting MultiTask." << endl;
}
// start the threads
void Start()
{
// Wait till they are finished
threads.join_all();
}
// stop the threads
void Stop()
{
// warning message
cout << "Stopping all threads." << endl;
// signal the threads to stop (thread-safe)
stopMutex.lock();
stop = true;
stopMutex.unlock();
// wait for the threads to finish
threads.interrupt_all();
threads.join_all();
}
void Callable_Out(int interval, int& count)
{
while (1)
{
//cout << "Callable_Out [" << count++ << "]" << endl;
boost::this_thread::sleep(boost::posix_time::millisec(interval));
boost::this_thread::interruption_point();
}
}
void Callable_In(int interval, int& count, string& userInput)
{
while (1)
{
cout << "Callable_In [" << count++ << "]. Enter message: ";
getline(cin, userInput);
boost::this_thread::sleep(boost::posix_time::millisec(interval));
boost::this_thread::interruption_point();
}
}
// Thread function
void operator () ()
{
while (1)
{
//cout << "Main [" << i_main++ << "]." << endl;
//cout << "Main [" << i_main++ << "]. " << userInput << endl;
if (userInput == "STOP")
{
try
{
this->Stop();
}
catch(exception e)
{
cout << e.what() << endl;
}
}
boost::this_thread::sleep(boost::posix_time::millisec(1000));
boost::this_thread::interruption_point();
}
}
};
int main()
{
MultiTask mt;
mt.Start();
}
However, VS throws two of these errors:
Severity Code Description Project File Line Suppression State
Error C2198 'void (__cdecl *)(boost::posix_time::millisec,int &,std::string &)': too few arguments for call mycpp c:\boost_1_66_0\boost\bind\bind.hpp 259
Can someone please help? This is from section 18.13. Also, I do not see where to input the arguments for CallableFunction() in that example. How can it be done in my case? Thanks.
In tutorial CallableFunction function takes only one parameter, it is passed as second parameter in thread constructor new boost::thread(&CallableFunction, i);.
In your case Callable_Out takes 2 parameters, one is missing, you should call
thread_output = new boost::thread(&Callable_Out, boost::posix_time::millisec(0), boost::ref(i_out));
and for Callable_In you call
thread_input = new boost::thread(&Callable_In, boost::posix_time::millisec(1), boost::ref(i_out), boost::ref(userInput));

libmosquittopp - sample client hangs on loop_stop() method

I'm trying to create a simple MQTT client for my home application and I'm using libmosquittopp (which is C++ version of libmosquitto).
There is not much of a documentation for this library, but I found 2 examples (here and here) that helped me to create a code for my "MQTTWrapper" class.
Here's my code:
MQTTWrapper.h :
#pragma once
#include <mosquittopp.h>
#include <string>
class MQTTWrapper : public mosqpp::mosquittopp
{
public:
MQTTWrapper(const char* id, const char* host_, int port_);
virtual ~MQTTWrapper();
void myPublish(std::string topic, std::string value);
private:
void on_connect(int rc);
void on_publish(int mid);
std::string host;
int port;
};
MQTTWrapper.cpp
#include "MQTTWrapper.h"
#include <iostream>
MQTTWrapper::MQTTWrapper(const char* id, const char* host_, int port_) :
mosquittopp(id), host(host_), port(port_)
{
mosqpp::lib_init();
int keepalive = 10;
if (username_pw_set("sampleuser", "samplepass") != MOSQ_ERR_SUCCESS) {
std::cout << "setting passwd failed" << std::endl;
}
connect_async(host.c_str(), port, keepalive);
if (loop_start() != MOSQ_ERR_SUCCESS) {
std::cout << "loop_start failed" << std::endl;
}
}
MQTTWrapper::~MQTTWrapper()
{
std::cout << "1" << std::endl;
if (loop_stop() != MOSQ_ERR_SUCCESS) {
std::cout << "loop_stop failed" << std::endl;
}
std::cout << "2" << std::endl;
mosqpp::lib_cleanup();
std::cout << "3" << std::endl;
}
void MQTTWrapper::on_connect(int rc)
{
std::cout << "Connected with code " << rc << "." << std::endl;
}
void MQTTWrapper::myPublish(std::string topic, std::string value) {
int ret = publish(NULL, topic.c_str(), value.size(), value.c_str(), 1, false);
if (ret != MOSQ_ERR_SUCCESS) {
std::cout << "Sending failed." << std::endl;
}
}
void MQTTWrapper::on_publish(int mid) {
std::cout << "Published message with id: " << mid << std::endl;
}
and my main():
#include <iostream>
#include <string>
#include "MQTTWrapper.h"
int main(int argc, char *argv[])
{
MQTTWrapper* mqtt;
mqtt = new MQTTWrapper("Lewiatan IoT", "my.cloudmqtt.host", 12345);
std::string value("Test123");
mqtt->myPublish("sensors/temp", value);
std::cout << "about to delete mqtt" << std::endl;
delete mqtt;
std::cout << "mqtt deleted" << std::endl;
return 0;
}
Sorry for so much code.
My problem is that when I compile it and execute - my application hangs infinitely (I only waited 9 minutes) in MQTTWrapper destructor on loop_stop() method.
Tested with libmosquittopp 1.4.8 (debian package) and then after removing it- with version 1.4.9 from github.
loop_start() and loop_stop(bool force=false) should start/stop a separate thread that handles messaging.
I have tested it with forced stop (loop_stop(true)) but this way my application stops and does not publish any data. loop_stop() on the other hand publishes the data but then halts.
console output (make && ./executable):
g++ -c MQTTWrapper.cpp
g++ -c main.cpp
g++ -o executable main.o MQTTWrapper.o -lmosquittopp
about to delete mqtt
1
Connected with code 0.
Published message with id: 1
(here it hangs infinitely...)
My question:
Why this loop_stop() hangs and how to fix it?
(any documentation/tutorial/example appreciated)
Try call disconnect() before loop_stop(). You should also bear in mind that you're effectively doing this:
connect_async();
loop_start();
loop_stop();
The client may not even have had chance to connect, nor the thread actually be started before you tell it to stop.
It's worth considering running actions in the callbacks:
on_connect -> call publish
on_publish -> call disconnect

c++ static string object crashes in release mode

I am attaching the minimal code below. The problem is with static string object that is leaking memory. I think the problem is with the string object not being initialized properly. The program runs fine in Debug mode but crashes in the Release mode.
I am using Windows 7 : 64bit - MS Visual Studio 2012
I have tried initializing the object with empty string but it did not solve the problem as suggested here
what to do if debug runs fine, but release crashes
I enabled "Treating warnings as Errors" also did not help as there are no warning as suggested by the following post
what to do if debug runs fine, but release crashes
There were some other suggestions too like "static initialization order fiasco" but I do not think its related to my issue.
Any help is appreciated
main.cpp
//main.cpp
#include "MyParameters.h"
using namespace std ;
int main( int argc, char *argv[] )
{
try
{
cout << "MyParameters::m_outputDir: " << MyParameters::m_outputDir << endl ;
bool initialized = MyParameters::initialize( "myimo.xml" ) ;
cout << "MyParameters::m_outputDir: " << MyParameters::m_outputDir << endl ;
cout << "Terminating the application..." << endl ;
}
catch ( std::exception &e )
{
cout << e.what() << std::endl;
}
}
MyParameters.h
//MyParameters.h
#ifndef __MY_PARAMETERS_H
#define __MY_PARAMETERS_H
#include <string>
#include <iostream>
#include <QString>
class MyParameters
{
public:
static std::string m_outputDir; ///< output directory
static bool initialize( const QString &xmlFile );
private:
MyParameters();
};
#endif /* __MY_PARAMETERS_H */
MyParameters.cpp
//MyParameters.cpp
#include "MyParameters.h"
#include <QDir>
std::string MyParameters::m_outputDir ;
using namespace std ;
MyParameters::MyParameters()
{
}
bool MyParameters::initialize( const QString &xmlFile )
{
m_outputDir = QDir::current().absoluteFilePath( xmlFile ).toStdString(); // --> this crashes
//m_outputDir = "C:\\Dev\\" ; // --> works fine
cout << "m_outputDir: " << m_outputDir << endl ;
cout << "myparameters.xml file reading is complete" << endl ;
return true;
}

How To Create TimerHandler Using Boost Library

I'm working on a project using C++.
I want a TimerHandler to be called after a specified time, but at the same time I don't want to block the current thread or any code after io.run() in the following code:
#include <iostream>
#include <string>
#include <boost/format.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
class TimerTest
{
public:
static void PrintOutTimerHandler(const boost::system::error_code&, const std::string& message)
{
std::cout << "PrintOutTimerHandler called: " << ", message: " << message << std::endl;
}
void run()
{
boost::asio::io_service io;
boost::asio::deadline_timer dt(io, boost::posix_time::seconds(5));
std::cout << "Start:\t" << std::endl;
dt.async_wait(boost::bind(PrintOutTimerHandler, boost::asio::placeholders::error, std::string("here is the message")));
// Do some job here
for (int i = 0; i < 1000000; ++i)
++i, --i;
std::cout << "End:\t" << std::endl;
io.run();
std::cout << "When to reach here 1: " << std::endl;
}
};
int main()
{
TimerTest tt;
tt.run();
std::cout << "When to reach here 2: " << std::endl;
return 0;
}
/* Current output:
Start:
End:
PrintOutTimerHandler called: , message: here is the message
When to reach here 1:
When to reach here 2:
*/
/* Expected output:
Start:
End:
When to reach here 1:
When to reach here 2:
PrintOutTimerHandler called: , message: here is the message
*/
I think I made myself clear. My questions are:
If this can be solved without
introducing a new thread, like Flex
ActionScript, that's is the best, but
I guess not (I guess ActionScript is
using a hidden thread);
If we have to
introduce an extra thread to do the
job, would you mind writing down the
pseudo code for me?
Thanks.
Peter
Here is an example . Run the io_service in a separate thread
asio::io_service io_service;
asio::thread t(boost::bind(&asio::io_service::run, &io_service));
or run it in a thread group
boost::thread_group threads;
for (std::size_t i = 0; i < my_thread_count; ++i)
threads.create_thread(boost::bind(&asio::io_service::run, &io_service));
Remember that your main thread should always run because when it exists all threads spawned will also exit.
I hope this helps.
I misunderstood what OrcunC said, but actually he is correct. Here is the modified version for your reference:
#include <iostream>
#include <string>
#include <boost/format.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
class TimerTest
{
public:
static void PrintOutTimerHandler(const boost::system::error_code&, const std::string& message)
{
std::cout << "PrintOutTimerHandler called: " << ", message: " << message << std::endl;
}
TimerTest(unsigned int timeout)
: dt(io, boost::posix_time::milliseconds(timeout))
{
}
void run()
{
std::cout << "Start:\t" << std::endl;
dt.async_wait(boost::bind(PrintOutTimerHandler, boost::asio::placeholders::error, std::string("here is the message")));
boost::thread thrd(boost::bind(&boost::asio::io_service::run, &io));
// Do some job here
for (int i = 0; i < 1000000; ++i)
++i, --i;
std::cout << "End:\t" << std::endl;
std::cout << "When to reach here 1: " << std::endl;
}
boost::asio::io_service io;
boost::asio::deadline_timer dt;
};
int main()
{
TimerTest tt(5000);
tt.run();
std::cout << "When to reach here 2: " << std::endl;
// Keep the main thread active for testing purpose. Otherwise,
// once the TimerTest object is destroyed when exiting the main() function,
// the sub thread spawed in tt.run() will also exit;
Sleep(10000);
}
/* Current output and Expected output:
Start:
End:
When to reach here 1:
When to reach here 2:
PrintOutTimerHandler called: , message: here is the message
*/