Segmentation fault trying to overload << operator - c++

Beginning with C++, I've written that simple piece of code, which is designed to serve as a (very basic) logger. This is mainly to try overloading operators.
class Logger {
public:
Logger() : _has_logged_something(false) { };
template <typename T>
friend Logger& operator <<(Logger& logger, T const & value) {
logger._has_logged_something = true;
std::cerr << value;
return logger;
};
private:
bool _has_logged_something;
};
I need to remember when something has been loaded already, in the _has_logged_something instance variable. But this line is causing a very helpful Segmentation fault (core dumped) at runtime. Must be an obvious mistake, but I can't get it.
--
Edit
As this doesn't seem to be a problem with this piece of code, here is how it is used to avoid using singletons (probably not the best code ever, but anyway).
#ifndef _BORDERS_COMMON_LOGGER_LOGGER_HH_INCLUDED
#define _BORDERS_COMMON_LOGGER_LOGGER_HH_INCLUDED
#include "common/log/logger.hh"
#include "common/log/event.hh"
namespace {
static borders::common::log::Logger* _global_logger = NULL;
}
namespace borders {
namespace common {
namespace log {
inline bool is_global_instance_initialized() {
return _global_logger != NULL;
};
inline Logger& get_global_instance() {
if (_global_logger == NULL) _global_logger = new Logger;
return *_global_logger;
};
} // namespace log
} // namespace common
} // namespace borders
#define LOG_INFO() (borders::common::log::get_global_instance())
#define LOG_START()
#define LOG_STOP() \
if (borders::common::log::is_global_instance_initialized()) \
delete &borders::common::log::get_global_instance(); \
else \
(void) 0;
#endif // _BORDERS_COMMON_LOGGER_LOGGER_HH_INCLUDED
Given I try to run this with:
LOG_INFO() << "Foo" << "Bar"
Once again, the text gets written on console when I comment out the line I pointed out before.

OK, I got it!
I think. At least I have a guess
See, that line logger._has_logged_something = true is the only line that used the data of the class logger. So my guess is that the class is invalid
I mean that you didn't really create that class. For some reason it wasn't really allocated.
For example if you did:
Logger *log; // see - I didn't put any value to it!
(*log)<<value; // this will do a segmentation fault or something
// ONLY if you have the line logger._has_logged_something = true
This is just an example. There are other options like:
struct blah{
blah(Logger &log):logger(log);
Logger &logger;
};
blah func(){
Logger log;
return blah(log);
}
...
blah b=func(); // b has an invalid logger in it, because it was destroyed after func
blah.logger << value ; // will do a segmentation fault too
Edit
Just saw your edit. So it seems to be my first example. Specifically, I believe you did LOG_STOP() before you logged.
Edit 2
You have an intrinsic problem in your code. LOG_STOP deletes the logger, but doesn't reset it to NULL. So if you want to restart logging after that, the logger won't be recreated (as get_global_instance checks if the logger is NULL before deciding to create it).
Try changing LOG_STOP to set _global_logger to NULL and see if that fixes it.

Related

'b_transport' is not a member of 'tlm_utils::simple_initiator_socket<...>' while trying to use TLM2

I am trying to use TLM2 for a simulation project but for some reason I can't use b_transport the same way I see it used in other projects, here is the code snippet that doesn't build due to this error(error C2039 : 'b_transport' : is not a member of 'tlm_utils::simple_initiator_socket<Initiator,32,tlm::tlm_base_protocol_types>')
#include <systemc.h>
#include <tlm_utils/simple_target_socket.h>
#include <tlm_utils/simple_initiator_socket.h>
SC_MODULE(Memory) {
tlm_utils::simple_target_socket<Memory> targetSocket;
SC_CTOR(Memory) {
targetSocket.register_b_transport(this, &BTransportCallback);
}
void BTransportCallback(tlm::tlm_generic_payload& payload, sc_time& delay) {
// ...
}
};
SC_MODULE(Initiator) {
tlm_utils::simple_initiator_socket<Initiator> initiatorSocket;
SC_CTOR(Initiator) {
}
};
SC_MODULE(TopLevel) {
Memory* memory;
Initiator* initiator;
SC_CTOR(TopLevel) {
memory = new Memory("Memory");
initiator = new Initiator("Initiator");
initiator->initiatorSocket.bind(memory->targetSocket);
// this is just an example for build test, obviously this isn't a correct call
tlm::tlm_generic_payload p;
initiator->initiatorSocket.b_transport(p, SC_ZERO);
}
};
I know what this error implies, but I don't understand why the systemc includes with tlm2 doesn't find this method.
I use SystemC 2.3.3 (Includes TLM), and there are no issues at includes, since I can use other systemc things normally.
Please let me know if you encountered something similar or what I might've overlooked(maybe I am using the wrong headers ?).
I found the issue. I had to use the arrow (->) operator, so this is the correct usage
SC_MODULE(TopLevel) {
Memory* memory;
Initiator* initiator;
SC_CTOR(TopLevel) {
memory = new Memory("Memory");
initiator = new Initiator("Initiator");
sc_time delay = SC_ZERO_TIME;
tlm::tlm_generic_payload p;
initiator->initiatorSocket.bind(memory->targetSocket);
initiator->initiatorSocket->b_transport(p, delay);
}
};

clang-format Function and error check in the same line

I struggle to set up clang-format to allow short lines for such format,
ierr = fun(); CHKERRQ(ierr);
clang-format break the line, as result
ierr = fun();
CHKERRQ(ierr);
It is a solution to stop clang-fromat to break short lines? Or this is in principle wrong idea to format code like this. Any advice very appreciated.
EDIT: Following Guillaume answer
In fact, I have a slightly more complex problem, where errors codes of different types are returned by two libraries, in particular, PETSc and MoAB. Also, this system has own error codes, which need to be handled. All without compromising efficiency.
struct ErrorCheckerCode {
inline void operator<<(const MoFEMErrorCode err) {
if (PetscUnlikely(err)) {
// Handle & thorw PETSc/MoFEM error
}
return;
}
inline void
operator<<(const moab::ErrorCode err) {
if (PetscLikely(MB_SUCCESS != err)) {
// Handle & trow MOAB error
}
return;
}
static const char *fUNC;
static const char *fILE;
static int lINE;
};
struct ErrorCheckerFunction {
inline ErrorCheckerCode operator<<(const char *func) {
ErrorCheckerCode::fUNC = func;
return ErrorCheckerCode();
}
};
struct ErrorCheckerFile {
inline ErrorCheckerFunction operator<<(const char *file) {
ErrorCheckerCode::fILE = file;
return ErrorCheckerFunction();
}
};
struct ErrorCheckerLine {
inline ErrorCheckerFile operator<<(int line) {
ErrorCheckerCode::lINE = line;
return ErrorCheckerFile();
}
};
And definition follows this:
#define CHKERR \
ErrorCheckerLine() << __LINE__ << __FILE__ << PETSC_FUNCTION_NAME <<
So at the end I can handle errors like this
CHKERR fun_moab();
CHKERR fun_petsc();
CHKERR fun_mofem();
This implementation is essential, so it has to be done optimally, I wonder if that can be done in simpler, more efficient way. Criticism or advice is very welcome.
Note:
As a commend. It is funny how formatting of code triggers this type of developments.
I use clang-format a lot and I don't think it can achieve this kind of formatting.
I've encountered this pattern a lot in libraries using OpenGL and DirectX. You have a API with error codes or an error stack like in OpenGL and every function might fail or issue a warning. You want your code to be optimized in release and still have a debug mode to find preciselly where things went wrong in case you spot a bug.
Some libraries provide some kind of error callback that you can set and will effectively be called each time there is a relevent error.
In case you want something more customized or no error callback is provided, you can write a simple wrapper that does a systematic error checking and warnings logging.
With these solutions you can even implement some mechanism to activate the debugging at runtime.
Now, if you are writing the library or functions that return errors returned this way, you might want to include the debug mode directly in the library with the debug callback strategy.
Now, if you want to stick to the macro solution, you could do the following:
struct ErrorChecker
{
ErrorChecker& operator << (int ierr)
{
// Error checking code
return *this;
}
};
#define CHKERR ErrorChecker() <<
and then
CHKERR fun();

Error handling when parsing text file to object

I want to parse a simple text file and create an object from the data it contains. I'm using C++11 for this (and I'm not fluent).
In case of any kind of error (e.g. missing file or invalid text) I wish to tell the caller of my parsing function what went wrong, providing information like what kind of error occurred and where in the file.
I don't consider exceptional that errors occur while parsing, so it seems exceptions are not the way to go.
I thought of returning a struct with all the info, including the resulting parsed object in case of success:
struct ParsingResult
{
bool success;
int errorCode;
int errorLine;
ParsedObject object;
}
However I'm not convinced by this solution because, in case of errors, I must still provide a ParsedObject. I can define a default constructor for that, of course, but by it's nature a ParsedObject makes sense only when the parsing is successful.
I could change ParsedObject to ParsedObject*, but I'm reluctant to use pointers when not necessary, and I wonder if this can be avoided.
My question: can you suggest a better solution to this problem? What is it?
struct Obj
{
// your object from the data...
}
struct ParseError
{
int errorCode;
int errorLine;
}
class Parser
{
ParseError m_error;
// other things
public:
bool parse(const std::string& filename, Obj& parsedObject)
{
// Open file, etc...
//parsedObject.property1 = some_value;
// if something is wrong, set m_error and return false;
// return true if ok
}
ParseError getLastError() { return m_error; }
}
// in your code
Parser p;
Obj o;
if(!p.parse("filename", o))
{
// ParseError = p.getLastError();
}
You can use a
unique_ptr<ParsedObject>
or
shared_ptr<ParsedObject>
whose default constructor can be compared to null in case of unsuccessful parsing.
Avoiding raw pointers will free you from having to free memory :)

Skip code without using state variable, using goto envisaged

I have a code which has parts that mustn't be executed if there was an error before in the code. I actually use a bool variable called EndProg that, if set to true, will instruct the program to avoid executing some parts of code.
My problem is that I don't want to use this method and I'd prefer to use goto instead because it will make the program jump to the cleanup part and avoid checking EndProg value multiple times.
The other problem is that I've read on many pages on StackOverflow and other websites that using goto is considered a bad practice and that it can make a code more difficult to read or create errors.
My code is simple enough and I will need to use just one label so I doubt that this will create problems; but I would like to know if there are other ways to do what I want without creating functions to do cleanup tasks or using return (because, for example, I will need to write the cleanup code several times) and I also don't want to write the same big cleanup code in multiple places and then use return or do something else.
I don't want to increase the number of lines of code nor use return nor use a lot of if nor check the value of a state variable. What would you recommend ?
Here's a piece of code :
bool EndProg=false;
/*
Lot of code that can set EndProg to true
*/
ClassType ClassName;
if(!EndProg && LoadConf(&ConfFilePath,&ClassName)==0)
{
int fildes=-1;
if(ClassName.abc) // bool
{
if(ClassName.FilePath==0) // char *
{
ClassName.FilePath=new(std::nothrow) char[9]();
if(ClassName.FilePath!=0)strcpy(ClassName.FilePath,"file.ext");
else EndProg=true;
}
if(!EndProg && mkfifo(ClassName.FilePath,S_IRUSR | S_IWUSR)==-1)
{
if(errno==EEXIST)
{
/* EEXIST is returned if the file already exists
We continue, later we will try to open this file */
}
else EndProg=true;
}
if(!EndProg && (fildes=open(ClassName.FilePath,O_RDWR))==-1)EndProg=true;
}
/*
Lot of code that will check if EndProg == true
*/
}
delete[] ClassName.FilePath;
delete[] ConfFilePath;
What I would like to do is :
bool EndProg=false;
/*
Lot of code that can set EndProg to true
*/
ClassType ClassName;
if(LoadConf(&ConfFilePath,&ClassName)==0)
{
int fildes=-1;
if(ClassName.abc) // bool
{
if(ClassName.FilePath==0) // char *
{
ClassName.FilePath=new(std::nothrow) char[9]();
if(ClassName.FilePath==0)goto cleanup;
strcpy(ClassName.FilePath,"file.ext");
}
if(mkfifo(ClassName.FilePath,S_IRUSR | S_IWUSR)==-1)
{
if(errno==EEXIST)
{
/* EEXIST is returned if the file already exists
We continue, later we will try to open this file */
}
else goto cleanup;
}
if((fildes=open(ClassName.FilePath,O_RDWR))==-1)goto cleanup;
}
/*
Lot of code that will check if EndProg == true
*/
}
cleanup:
delete[] ClassName.FilePath;
delete[] ConfFilePath;
As you can see it isn't difficult to understand and even if searching the label can be a problem for someone, it isn't for me; and I don't plan to make the code public.
Update :
I decided to using exceptions and it works for some parts of my original code. But I doubt this will be easy to implement in more complex parts. Thanks for your answers.
Since you've tagged this question c++ as well I'd go with using exceptions and a try catch block.
You can find a lot of useful information about the subject on SO and on other websites:
Here is a very basic tutorial.
And here is a nice and basic FAQ that might help you as well.
Basically there's nothing to fear, exceptions are not cryptic and in fact make more sense when you get the hang of it. Because basically this concept enables you to achieve exactly what you want:
Several pitfalls that can be handled by the same error handling code.
Edit:
For example if I'd move the mkfifo etc. into a function (in general creating a function for each well defined logical block is clearer and more readable) and have something like
This is just a sketch to give you a general idea:
#include <exception>
functionThatDoesMakeFifo(...){
// check which ever conditions you want to check after mkfifo
// if one of them goes wrong just do:
throw std::exception();
}
// this is inside your function:
ClassType ClassName;
try{
ClassName.FilePath = new char[9](); // even though I'd use a string...
.
.
. // rest of the code
} catch(std::exception &e){
delete [] ClassName.FilePath;
delete [] ConfFilePath;
ClassName.FilePath = NULL; // not mandatory just my habit
ConfFilePath = NULL;
}
I would try with something like Scope Guards or BOOST_SCOPE_EXIT (C++) or its C++11 analogue:
template<class F>
struct ScopeExit
{
ScopeExit(F f) : f(f) {}
~ScopeExit() { f(); }
F f;
};
template<class F>
ScopeExit<F> MakeScopeExit(F f) { return ScopeExit<F>(f); }
#define STRING_JOIN2(arg1, arg2) DO_STRING_JOIN2(arg1, arg2)
#define DO_STRING_JOIN2(arg1, arg2) arg1 ## arg2
#define SCOPE_EXIT(code) \
auto STRING_JOIN2(scope_exit_, __LINE__) = MakeScopeExit([=](){code;})
bool myfunct()
{
ClassType ClassName;
ClassName.FilePath = 0;
ConfFilePath = 0;
SCOPE_EXIT(delete [] ClassName.FilePath; delete [] ConfFilePath; );
if (LoadConf(&ConfFilePath,&ClassName) == 0)
{
int fildes=-1;
if(ClassName.abc) // bool
{
if(ClassName.FilePath==0) // char *
{
ClassName.FilePath=new(std::nothrow) char[9]();
if(ClassName.FilePath==0) return false;
strcpy(ClassName.FilePath,"file.ext");
}
if(mkfifo(ClassName.FilePath,S_IRUSR | S_IWUSR)==-1)
{
if (errno==EEXIST)
{
/* EEXIST is returned if the file already exists
We continue, later we will try to open this file */
}
else return false;
}
if((fildes=open(ClassName.FilePath,O_RDWR))==-1) return false;
}
/*
Lot of code that will check if EndProg == true
*/
}
return true;
}
I'm using return but the cleanup code is just in one place.
Anyway ClassName should take care of cleaning up its own resources in the destructor.
There is a little trick I have seen before that might help you solve this, although I am personally not a fan of tricks, it might be appropriate for what you require.
while (true)
{
if(ClassName.FilePath==0) // char *
{
ClassName.FilePath=new(std::nothrow) char[9]();
if(ClassName.FilePath==0) break;
strcpy(ClassName.FilePath,"file.ext");
}
if(mkfifo(ClassName.FilePath,S_IRUSR | S_IWUSR)==-1)
{
if(errno==EEXIST)
{
/* EEXIST is returned if the file already exists
We continue, later we will try to open this file */
}
else break;
}
if((fildes=open(ClassName.FilePath,O_RDWR))==-1) break;
/*
Lot of code that will check if EndProg == true
*/
break;
}
delete[] ClassName.FilePath;
delete[] ConfFilePath;
But again I am not condoning this as a graceful solution, I personally would re-write your code and break it down into something more readable.
But then again I don't write functions containing hundreds of lines either.
I may get downvoted for this, but I think that limited use of goto in C is not evil. Particularly, what you are talking about is quite acceptable: branching forward to clean up code on errors. I'd suggest that you limit this to a single target label per routine.
What people hate (justifiably) is the old fastion spaghetti code with goto's jumping all over the place.

Stop evalulate operator<<

I am trying to do a simple logging library only for my own. I know there exists several once, but I have not found any header-only, small and very "c++" like logging library which fits into my application.
Currently I have the following syntax:
logger << debug << "A debug message" << end; //debug and end is my custom manipulators
I have implemented all necessary operator<< and it works great, specially when it have backward compatibility with std::ostream. But I wonder, just for efficiency if it is a why to stop evaluate anything if some message should not be logged (after debug in the example)? Making everything after the severity manipulator "disappear"?
Just now do I have the following code in short:
template <typename Type>
Logger & Logger::operator<<(const Type & message)
{
if(this->get_message_level() <= this->get_severity())
{
BOOST_FOREACH(std::ostream* stream, this->_sinks)
{
*stream << message;
}
}
return *this;
}
Logger & Logger::operator<< (Logger & (*pf)(Logger&))
{
return pf(*this);
}
Logger & debug(Logger& logger)
{
logger.lock();
logger.set_severity(7);
//...
return logger;
}
Logger & end(Logger& logger)
{
logger << std::endl;
logger.unlock();
return logger;
}
Thanks in advance.
You could do something as simple as
extern "C" bool want_log;
#define LOG(Arg) do { if (want_log) \
cout << __FILE__ << ":" << __LINE__ ": " << Arg << endl; } while(0)
and use it as LOG("x=" << x)
It can be a bit tricky, depending on what compromizes you're willing to
accept in the syntax. If you really want to support everything that
outputting to an ostream does, then the best you can do (as far as I
know) is a wrapper class, along the lines of:
class Logger
{
std::ostream* myDest;
public:
// Appropriate constructors...
template<typename T>
Logger& operator<<( T const& obj )
{
if ( myDest != NULL )
(*myDest) << obj;
return *this;
}
};
If logging is turned off (Logger::myDest == NULL), none of the
conversion code will execute, but you'll still evaluate each of the
arguments. In my experience, this is not usually an issue, since most
of the arguments are either string literals or a simple variable, but
it's not a total 0 cost. It also has the potential disadvantage that
the propagated type is not std::ostream& (although I've never found
this to be a problem in practice).
A somewhat tricker solution would be to use a macro along the lines of:
#define logger loggerInstance != NULL && (*loggerInstance)
This will still allow most of the actual uses with the same syntax
(because the && operator has very low precedence), but could fail in
cases where someone has tried to be too clever, and embedded the logging
output in a more complicated expression. In addition to not doing the
conversions, the arguments are not even evaluated if logging is turned
off.
Finally, if you accept a different syntax, you can write something like:
#ifndef NDEBUG
#define LOG(argList) logger << argList
#else
#define LOG(argList)
#endif
This requires the user to write LOG("x = " << x), instead of log <<
"x = " << x, and requires recompiling if you want to turn logging on,
but it is the only solution I know which has absolute 0 cost if logging
is turned off.
In my experience, most applications can support the first solution; in a
very few cases, you might want to use the second; and I've never seen an
application where performance required the third.
Note that even with the first, you'll probably want to use a macro to
get the logger instance, in order to automatically insert __FILE__ and
__LINE__, and that in the second, you'll probably still want to use a
wrapper class, in order to ensure a flush in the destructor; if the
application is multithreaded, you'll want the wrapper in all cases, in
order to make the entire sequence of output atomic.
You could check for the severity in the Logger & Logger::operator<< (Logger & (*pf)(Logger&)) operator and just return an "empty" logger that doesn't print anything in that case:
class EmptyLogger : public Logger {
template <typename Type>
Logger & Logger::operator<<(const Type & message) { return *this; }
};
EmptyLogger empty; // Can be global/static, it won't cause any race conditions as it does nothing
Logger & Logger::operator<< (Logger & (*pf)(Logger&))
{
if (logger.get_severity() < 5) // Replace with a proper condition
return empty;
return pf(*this); // What does pf() do? Aren't you returning reference to a temporary object?
}
Take a look at this article in dr dobbs about logging in c++:
http://drdobbs.com/cpp/201804215?pgno=2
This page addresses your particular concern but I'd recommend reading the whole article.
I implemented a logging system based on this article and was really pleased with it.