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;
}
Related
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.
I wrote a program that copy a file from a given path(s) to another. It runs well until it meets special character in directory names or in file names. At that moment it stops and throws the error that "No such file or directory".
This is what I done until now:
#include <iostream>
#include <vector>
#include <filesystem>
#include <cxxabi.h>
#include <string>
#include <sstream>
#include <memory>
#include <windows.h>
#include <chrono>
#include <thread>
using namespace std;
namespace fs = std::filesystem;
int main(int argc, char **argv) {
vector<string> args(argv + 1, argv + argc);
auto target = args[args.size() - 1];
fs::path path = target;
cout << "Destination path: " << target << endl;
args.erase(args.end());
for (const auto &source : args) {
try {
for (const auto &entry : fs::recursive_directory_iterator(source)) {
std::string new_path = target + "\\" + entry.path().relative_path().string();
//if entry is directory:
while (true) {
if (GetDriveType(const_cast<char *>(path.root_path().string().c_str())) != DRIVE_NO_ROOT_DIR) {
if (fs::is_directory(entry)) {
//only if it NOT exists:
if (!fs::exists(new_path)) {
//create it only if not empty:
if (!fs::is_empty(entry)) {
//Creating directory tree structure with empty folders:
try {
fs::create_directories(new_path);
} catch (const std::exception &e) // caught by reference to base
{
std::cout << "When trying to create directory" << new_path
<< "A standard exception was caught, with message '"
<< e.what() << "'\n";
}
}
}
}
break;
} else {
cout << "Destination path is not available. Sleeping for 3 minutes!" << endl;
std::this_thread::sleep_for(180000ms);
}
}
while (true) {
if (GetDriveType(const_cast<char *>(path.root_path().string().c_str())) != DRIVE_NO_ROOT_DIR) {
if ((fs::is_regular_file(entry)) && (fs::exists(entry))) {
if (!fs::is_empty(entry)) {
if (!fs::exists(new_path)) {
//file does NOT exists in new path:
try {
fs::copy_file(entry.path().string(), new_path);
cout << "Copy file: " << entry.path().string() << endl;
fs::remove(entry);
} catch (const std::exception &e) // caught by reference to base
{
std::cout
<< "When trying to get file size and source a standard exception was caught, with message '"
<< e.what() << "'\n";
}
} else {
//if it exists in new path:
//first try to get file size and if this gives an error then do not copy:
if (fs::file_size(entry.path().string()) >
fs::file_size(entry.path().string())) {
try {
fs::copy_file(entry.path().string(), new_path);
cout << "Replacing file: " << entry.path().string() << endl;
fs::remove(entry);
} catch (const std::exception &e) // caught by reference to base
{
std::cout
<< "When trying to get file size and source a standard exception was caught, with message '"
<< e.what() << "'\n";
}
}
}
}
}
break;
} else {
cout << "Destination path is not available. Sleeping for 3 minutes!" << endl;
std::this_thread::sleep_for(180000ms);
}
}//end while!
}
} catch (const std::exception &e) // caught by reference to base
{
std::cout << "When recursive through directory tree a standard exception was caught, with message '"
<< e.what() << "'\n";
}
}
return 0;
}
After searching on Google and mostly on stackoverflow for a solution conclusion is that none works.
I tried adding #define UNICODE and #define _UNICODE at the top of it but it gives even more errors.
I also added -municode flag in CMakeLists in CLion but also not working (it compiles but gives runtime error).
Also tried to replace all possible string to wstring or wchar_t * with L"where possible" and to convert this entry.path().relative_path().string() to entry.path().relative_path().wstring() and also cout to wcout. Still not working.
Also changed main to wmain( int argc, wchar_t *argv[ ]) or to wmain( int argc, wchar_t *argv[ ], wchar_t *envp[ ] ) and still not working.
Also added setlocale(LC_ALL, ""); after the main function as the other article on stackoverflow says and still no improvement.
I am asking for help because I didn't find a solution for this problem and also, more of the other solution are for printing special unicode characters to console but I need more to work with them (read files names and paths that contain special unicode characters) instead of printing them.
More than this, after I tried all of these possible not working solutions I am talking about above and reverted my program back to the original code that I just posted above now it is not working at all. It says "no such file or directory" even for normal latin characters and doesn't copy or delete anything at all anymore.
Go to the header file in which std::filesystem::path is defined.
(possibly in: PATH_TO_MINGW/usr/include/c++/YOUR_VERSION/bits/fs_path)
Look for using value_type =
Look for compiler macros that define which value_type is ultimately used.
an example from the version from my system:
#ifdef _GLIBCXX_FILESYSTEM_IS_WINDOWS
using value_type = wchar_t;
static constexpr value_type preferred_separator = L'\\';
#else
When the macro _GLIBCXX_FILESYSTEM_IS_WINDOWS is set to 1 then a wchar_t will be used, which should solve your issue.
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!
I have an application that creates a directory and copy a file to it. This is working fine, normally. But if the window shuts down correctly and the power is lost, the files will not always be available or complete.
My OS is Windows Embedded POSReady7 (Version 6.1 Build 7601: Service Pack 1) and on the hard disk is "write caching" option disabled. I have a C++ Application. I used also _flushall but it doesn't help.
I have written a test application where I can see the problem. I start the application, wait ten seconds after the output is completed and then unplug the power. The files are not available after restart.
Here is my code:
#include "stdafx.h"
#include <iostream>
#include <direct.h>
#include <string>
#include <Windows.h>
#include <atlstr.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
string csPathName("D:\\temp\\FileCopyTest\\");
int mkRetValue = _mkdir( csPathName.c_str() );
cout << "Create directory " << csPathName.c_str() << " with return value " << mkRetValue << endl;
BOOL copyRetValue = CopyFileEx( _T("D:\\temp\\test.txt"), _T("D:\\temp\\FileCopyTest\\test.txt"), nullptr, nullptr, FALSE, COPY_FILE_NO_BUFFERING );
cout << "Copy file, return value " << copyRetValue << endl;
int flushRetValue = _flushall();
cout << "flush files: " << flushRetValue << endl;
char c;
cin >> c;
return 0;
}
Have you tried putting copy within the scope?
{
CopyFileEx( _T("D:\\temp\\test.txt"), _T("D:\\temp\\FileCopyTest\\test.txt"), nullptr, nullptr, FALSE, COPY_FILE_NO_BUFFERING );
}
I have a problem when i use mysql connector c++ and visual studio on the debug mode. It compiles just fine. My algorithm works on release mode. When i switch to debug mode, he complies but he crash while running.
I believe that he crash each time i use res->getString() .
I m using visual studio 2013, mysql connector.C++ 1.1 . I already added the dependencies
C:\Program Files\MySQL\Connector.C++ 1.1\lib\debug
C:\Program Files\Boost SDK;
C:\Program Files\MySQL\Connector.C++ 1.1\include
mysqlcppconn.lib and mysqlcppconn.dll
CPPCONN_PUBLIC_FUNC= ;HAVE_INT8_T=1 ( on the processor definition)
run time library : /MDd ( it the only think that works )
I copied mysqlcppconn.lib and mysqlcppconn.dll in the debug directory of my project
with this configuration my programm works on release mode ( changing Connector.C++ 1.1\lib\debug to Connector.C++ 1.1\lib\opt ).
In the debug mode, he says Debug Assertion failed :
File: f:\dd\vctools\crt\crtw32\misc\dbgheap.c
Line 1322
Expression : _CrtIsValidHeapPointer( pUserData)
Press Rety to debug the application
then i had to choose one buttom ( Ignore; Restart ; leave ). When i press Ignore he continue to run i have the first results but he crashs again
This is my code section
{
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <memory>
#include <string>
/* MySQL Connector/C++ specific headers */
#include <cppconn/driver.h>
#include <cppconn/connection.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/resultset.h>
#include <cppconn/metadata.h>
#include <cppconn/resultset_metadata.h>
#include <cppconn/exception.h>
#include <cppconn/warning.h>
#include "mysql_connection.h"
using namespace std;
using namespace sql;
int main(int argc, const char **argv)
{
const char* str_DataBaseMarketData_Server = "root";
const char* str_DataBaseMarketData_User = "root";
const char* str_DataBaseMarketData_Password ="root";
const char* str_DataBaseMarketData_Database ="bd test";
cout << "Connector/C++ tutorial framework..." << endl;
cout << endl;
string fld;
try {
sql::Driver* driver = get_driver_instance();
std::auto_ptr<sql::Connection> con(driver->connect(str_DataBaseMarketData_Server, str_DataBaseMarketData_User, str_DataBaseMarketData_Password));
con->setSchema(str_DataBaseMarketData_Database);
std::auto_ptr<sql::Statement> stmt(con->createStatement());
sql::SQLString *data = new SQLString();
std::auto_ptr<sql::ResultSet> res(stmt->executeQuery("SELECT * FROM news "));
//ResultSetMetaData *res_meta = res->getMetaData();
//cout << res_meta->getColumnDisplaySize( 1) << endl << endl;
while (res->next()){
fld = res->getString(2).c_str();
}
}
catch (sql::SQLException &e) {
/*
The MySQL Connector/C++ throws three different exceptions:
- sql::MethodNotImplementedException (derived from sql::SQLException)
- sql::InvalidArgumentException (derived from sql::SQLException)
- sql::SQLException (derived from std::runtime_error)
*/
cout << "# ERR: SQLException in " << __FILE__;
cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
/* Use what() (derived from std::runtime_error) to fetch the error message */
cout << "# ERR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << " )" << endl;
return EXIT_FAILURE;
}
cout << "Done." << endl;
return EXIT_SUCCESS;
}
}
This things turns me crazy because when i replace getString() by anything else, it works sweetly.Could you help me please ?
I m running under a 32 bit.