Unhandled exception when application is finishing - c++

I have a singleton (I know that is a bad pattern). To control the cleaning process, I'm using a shared pointer. The relevant code is:
#ifndef _GLOBAL_LOG_H_
#define _GLOBAL_LOG_H_
namespace glog{
class CGlobalLog;
typedef boost::shared_ptr<CGlobalLog> globalLogPtr;
class CGlobalLog
{
private:
static globalLogPtr m_instance;
LogLevel minimiumLogLevel;
CGlobalLog(void);
static void deleter(CGlobalLog *ptr){
try{
delete ptr;
}
catch(std:: e)
{
std::cout << e.what() << "\n";
}
}
static void create() { m_instance.reset( new CGlobalLog, &CGlobalLog::deleter ); }
void addMessage_(const std::string& appender, LogLevel level /*= LOGLEVEL_INFO*/,const char* msg, va_list args );
~CGlobalLog(void);
public:
static globalLogPtr& getInstance();
void addMessage(const std::string& message, std::string appender, LogLevel level = LOGLEVEL_INFO);
};
globalLogPtr CGlobalLog::m_instance;
};
#endif // _GLOBAL_LOG_H_
The program works fine, but when program finish, an unhandled exception is thrown in this point:
static void deleter(CGlobalLog *ptr){
try{
delete ptr; //<-- Unhandled exception
}
catch(std:: e)
{
std::cout << e.what() << "\n";
}
}
The catch doesn't catch the exception so I don't know what to do to profile my error. The exact code where error is throw is a boost library file checked_delete.hpp, here:
// verify that types are complete for increased safety
template<class T> inline void checked_delete(T * x)
{
// intentionally complex - simplification causes regressions
typedef char type_must_be_complete[ sizeof(T)? 1: -1 ];
(void) sizeof(type_must_be_complete);
delete x;
}
How do I need to locate this error? Some ideas?
Thanks!!!

I generally don't expect to see a shared pointer on a singleton. Just returning a reference to your singleton and never keeping a reference to it laying around is a good practice.
struct Foo {
static Foo &instance() {
static Foo foo;
return foo;
}
};
struct Bar {
void someMethod() {
Foo &foo = Foo::instance(); // just grab a reference every time you need it
// ...
}
};
If you wish to keep the shared pointer and need to clean up resources in manual way, create a tear down method. The boost::shared_ptr will clean up the memory eventually.
Personally, I think using a shared pointer externally is inferior. I wrote some code to demonstrate a tear down and it didn't seem generally applicable without knowing why you need one.
If you want an explicit delete, then write one.
struct Foo {
static Foo *foo = 0;
static Foo &instance() {
if (!foo)
throw std::logic_error("Already deleted");
return *foo;
}
static void Init() {
if (foo)
throw std::logic_error("Already created");
foo = new Foo;
}
static void Destroy() {
if (!foo)
throw std::logic_error("Already deleted");
delete foo;
foo = 0;
}
};
In the case of logging, the logic errors should be superfluous. If logging isn't valid when you ask for it, then it is unlikely that your application is in a valid state.

Related

Passing dependency in allocator

I've been making interpreter for prototype-based language .
And i found problem i dont know how to solve .
Objects are splited into actual object and object map with slots. Both of them are allocated into heap that is under control of GC.
Implementation of operator new in Object and ObjectMap are practically same:
void* Objects::Object::operator new(size_t size) {
return Universe::getUniverse()->allocateMemory(size);
}
Universe is implemented as singleton that contains pointer to other parts of virtual machine (interpreter , object heap etc.).
This design cant be used with unit tests so i wanted to rewrite it into something like this soo i will be able to inject different heap during testing:
void* Objects::Object::operator new(size_t size, ObjectHeap* objectHeap) {
return objectHeap->allocateMemory(size);
}
But i found problem.
Object is creating new ObjectMap in constructor (ObjectMap is using same implementation of operator new):
Objects::Object::Object(unsigned char numberOfSlots) {
this->forwadingPointer = nullptr;
this->objectMap = new Object_Layout::ObjectMap(numberOfSlots);
}
Is there any way to pass that injection into allocator for ObjectMap (when i create Object using heap , Object Map created by Object will be in same heap) ?
This method will allow you to use a custom memory manager for everything in your unit tests.
You can't use new inside your custom memory manager or it will cause infinite recursion, though.
universe..hh
class Universe
{
public:
static Universe * getUniverse();
};
universe.cc
#include "universe.hh"
Universe * Universe::getUniverse() {
return new Universe;
}
main.cc
#include "universe.hh"
namespace myalloc {
class IAllocator
{
public:
virtual void * allocateMemory (size_t size) = 0;
};
//
// Your heap
//
class MyAllocator : public IAllocator
{
public:
void * allocateMemory (size_t size) {
return ::malloc(size); // call your heap allocator (not 'new'!)
}
};
//
// Unit testing heap
//
class DebugingAllocator : public IAllocator
{
public:
enum e_modes {
e_alloc, // 0 will get memory
e_bad_alloc
};
void setMode (int m) { _mode = m; }
void * allocateMemory (size_t size) {
void * buf {nullptr};
switch (_mode) {
case e_bad_alloc:
throw std::bad_alloc();
break;
case e_alloc:
default:
buf = ::malloc(size); // my testing allocator
break;
}
return buf;
}
private:
int _mode {0};
};
class MyAllocatorHandler {
public:
static void setAllocator (IAllocator * allocatorMock) {
_allocator_ptr = allocatorMock;
}
static IAllocator * getAllocator () { return _allocator_ptr; }
private:
static MyAllocator _allocator;
static IAllocator * _allocator_ptr;
};
MyAllocator MyAllocatorHandler::_allocator;
IAllocator * MyAllocatorHandler::_allocator_ptr {&MyAllocatorHandler::_allocator};
} // end namespace myalloc
#ifdef UNIT_TEST
void * operator new (size_t size) {
std::cerr << "Debug new operator. Alloc " << size << " bytes." << std::endl;
return myalloc::MyAllocatorHandler::getAllocator()->allocateMemory(size);
}
void operator delete (void * buf) {
std::cerr << "Debug delete operator." << std::endl;
::free (buf);
}
#endif
int main ()
{
// create a unit test allocator
myalloc::DebugingAllocator da;
// change allocator to simulate error conditions
myalloc::MyAllocatorHandler::setAllocator (&da);
// no failure for allocation
Universe * univ = Universe::getUniverse();
// set failure mode
da.setMode (myalloc::DebugingAllocator::e_bad_alloc);
try {
// it will fail even in other libraries...
//std::string str ("This is a long sentence to avoid small buffer optimizations.");
std::cout << "Try to allocate." << std::endl;
Universe * univ1 = Universe::getUniverse();
// we aren't going to arrive here in UNIT_TEST mode
std::cout << "Can't we see this?"
<< std::endl;
delete univ1;
} catch (std::bad_alloc & ex) {
std::cerr << "Bad alloc, as expected." << std::endl;
}
delete univ;
return 0;
}
Ok only way to do this is using factory method to create objects
Objects::Object* Objects::Object::create(Memory::ObjectSpace* memory, unsigned char numberOfSlots){
return new(memory) Object(memory, numberOfSlots);
}
I will pass memory object that i want use and static method will pass it into allocator and constructor.
Constructor will pass memory parameter into constructor of ObjectMap.
Objects::Object::Object(Memory::ObjectSpace* memory, unsigned char numberOfSlots) {
this->forwadingPointer = nullptr;
this->objectMap = new(memory) Object_Layout::ObjectMap(memory, numberOfSlots);
}
It will be better to add factory method into ObjectMap too.
Thanks to Silvio Mayolo for idea.

Trying to access an object that is being destroyed

I have an object which contains a thread which indirectly accesses this object like so:
#include <iostream>
#include <thread>
#include <atomic>
class A;
class Manager
{
public:
Manager(void) = default;
void StartA(void)
{
a = std::make_unique<A>(*this);
}
void StopA(void)
{
a = nullptr;
}
A& GetA(void)
{
return *a;
}
private:
std::unique_ptr<A> a;
};
class A
{
public:
A(Manager& manager)
: manager{manager},
shouldwork{true},
thread{[&]{ this->Run(); }}
{
}
~A(void)
{
shouldwork = false;
thread.join();
}
private:
Manager& manager;
std::atomic<bool> shouldwork;
std::thread thread;
void Run(void)
{
while (shouldwork)
{
// Here goes a lot of code which calls manager.GetA().
auto& a = manager.GetA();
}
}
};
int main(int argc, char* argv[])
try
{
Manager man;
man.StartA();
man.StopA();
}
catch (std::exception& e)
{
std::cerr << "Exception caught: " << e.what() << '\n';
}
catch (...)
{
std::cerr << "Unknown exception.\n";
}
The problem is that when one thread calls Manager::StopA and enters destructor of A, the thread inside A segfaults at Manager::GetA. How can I fix this?
In StopA() you set a = nullptr;, this in turn destroys the a object and all further access to its members result in undefined behaviour (a likely cause the segmentation fault).
Simply moving the a = nullptr; to the destructor of the Manager could resolve this problem. Even better, allow the RAII mechanism of the std::unique_ptr to destroy the a object when the destructor of the Manager runs (i.e. remove the line of code completely).
With active object implementations, careful control of the member variables is important, especially the "stop variable/control" (here the shouldwork = false;). Allow the manager to access the variable directly or via a method to stop the active object before its destruction.
Some of the code here looks out of place or obscure, e.g. a = std::make_unique<A>(*this);. A redesign could help simplify some of the code. The Manager class could be removed.
class A
{
public:
A(): shouldwork{true}, thread{[&]{ this->Run(); }}
{
}
void StopA()
{
shouldwork = false;
thread.join();
}
private:
std::atomic<bool> shouldwork;
std::thread thread;
void Run(void)
{
while (shouldwork)
{
// code...
}
}
};
The code is modelled along the lines of std::thread, were the stopping of the tread is more controlled before an attempt is made to join it. The destructor is left empty in this case, to mimic the termination (calling std::terminate) result, as is the case with the standard thread library. Threads must be explicitly joined (or detached) before destruction.
Re-introducing the Manager, the code could look as follows;
class A
{
public:
A() : shouldwork{true}, thread{[&]{ this->Run(); }} {}
void StopA() { shouldwork = false; thread.join(); }
private:
void Run();
std::atomic<bool> shouldwork;
std::thread thread;
};
class Manager
{
public:
Manager() = default;
void StartA(void)
{
a = std::make_unique<A>();
}
void StopA(void)
{
a->StopA();
}
A& GetA(void)
{
return *a;
}
private:
std::unique_ptr<A> a;
};
void A::Run()
{
while (shouldwork)
{
// Here goes a lot of code which calls manager.GetA().
auto& a = manager.GetA();
}
}
And your main remains as it is.

Where am I supposed to catch the C++ exception thrown in the constructor?

Header file:
#ifndef MUTEXCLASS
#define MUTEXCLASS
#include <pthread.h>
class MutexClass
{
private:
pthread_mutex_t & _mutexVariable;
public:
MutexClass (pthread_mutex_t &);
~MutexClass ();
};
#endif // MUTEXCLASS
Source file:
#include "mutexClass.h"
#include <stdexcept>
MutexClass::MutexClass (pthread_mutex_t & arg) : _mutexVariable (arg)
{
_mutexVariable = PTHREAD_MUTEX_INITIALIZER;
int returnValue = pthread_mutex_lock (&_mutexVariable);
if (returnValue > 0)
{
throw std::logic_error ("Mutex couldn't be locked!");
}
}
MutexClass::~MutexClass()
{
pthread_mutex_unlock (&_mutexVariable);
}
Where am I supposed to catch the exception thrown in the constructor?
An exception thrown in a constructor can be handled
by the code explicitly creating the object (try { MutexClass m; ... } catch(const std::logic_error& e) { ... })
by code creating an object that contains as member a MutexClass instance (including as base sub-object... i.e. by code that creates an object derived from MutexClass)
by code calling code doing the creation as exceptions will un-wind the stack until some code handles them
Note that for exceptions thrown in constructor of objects that are members of bigger objects (either for an has-a or a is-a relationship) there is a tricky part. The destructor of the bigger object will not be called if the costruction of a member throws an exception... only the already constructed members will be destroyed before propagating the exception. For example a class like:
struct Foo {
MyData * data;
MutexClass m;
MyData() : data(new int[1000]) { }
~MyData() { delete[] data; } // NOT called if m constructor throws
};
will leak memory if MutexClass constructor throws an exception.
Also before writing an exception handler however ask yourself if catching the exception is the right thing to do (i.e. if you know what to do when that condition occurs). Catching an exception and "hiding" it because you don't know what to do in that case is the worst possible choice.
In the specific case if you cannot lock a freshly created mutex can you expect the system to be still in good enough shape that keeping it running is a good idea?
As with any exception, anywhere up the stack where you can handle the exception. This is no way different from handling exceptions thrown in functions.
At the point of construction
try {
MutexClass m(arg);
}catch( std::logic_error const & e)
{
}
or if you have a pointer
try {
MutexClass * m = new MutexClass(arg);
}catch( std::logic_error const & e)
{
}
If you were able work with a pointer , passed to a function , surround the function.
E.g.
void funfun ( MutexClass * );
try {
funfun(new MutexClass(arg));
}catch( std::logic_error const & e)
{
}
If you are going to construct the object in an initializer list:
class A
{
MutexClass mc;
A(pthread_mutex_t & m) try : mc(m)
{
} catch ( std::logic_error const & e )
{
// do something here to handle the failure
// of mc(m) and the now the failure of A
// must be handled in the construction point of A
}
};
But now you have to handle the failure of the constructor of A as well.
Furthermore you should watch out for implicit conversions and copies, and you class is sadly copiable.
void funfun(MutexClass m );
pthread_mutex & m;
try
{
void funfun(m);
} catch( std::logic_error const & e )
{
}
Read before throwing from a constructor.
Also don't forget that such constructors are not good as static members.
So this type of class may break your program
class maybreak
{
private:
static MutexClass mc;
// ....
};
unless a wrapper function method is defined to put the construction of the static after your program actually starts (COFU).

Macro to return the 'this' pointer, or NULL when it's not available

Is it possible to access the this pointer in non-static context and use something else in static context automatically? Do you know any macro or template magic?
#define LOG std::cout << _is_the_this_pointer_available_ ? this : 0
class Foo {
void test() {
LOG;
}
};
void staticTest() {
LOG;
}
Do you know any macro or template magic?
Honestly, I wouldn't do this with a macro. When something can be done without macros, I'd suggest to prefer avoiding them. Here is a possible solution based on overloading, CRTP, and inheritance (no macros):
int get_this() { return 0; }
template<typename T>
struct get_this_helper
{
T* get_this() { return static_cast<T*>(this); }
};
The only overhead is that you have to make your classes derive from the proper specialization of get_this_helper<>, as shown below:
#include <iostream>
#define LOG std::cout << get_this() << std::endl;
class Foo : public get_this_helper<Foo> {
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// This is the only thing that requires
// being changed wrt your version of Foo
public:
void test() {
LOG;
}
};
void staticTest() {
LOG;
}
Here is a simple test program:
int main()
{
Foo f;
f.test();
staticTest();
}
And a live example.
I am using the following technique to write this pointer to a log:
#define GET_THIS() __if_exists(this) { this; } __if_not_exists(this) { nullptr; }
However it is Microsoft specific.
#define LOG std::cout << isThisAvailable()
bool isThisAvailable() { return false; }
struct X
{
bool isThisAvailable() { return true; }
void test() { LOG; }
};
void staticTest()
{
LOG;
}
Calling isThisAvailable inside the class will return true. Calling outside the class context will call the free function and return false.

Remove the defines in this safeguard mutex example

-edit- i cant experiment ATM but will tonight. I am thinking maybe a typedef can be used to hold mut and can be used to declare a var. But my initial thought is typedefs don't play nice with templates so i'll have to check later tonight (for now, to class)
I was looking at this piece of code shown below and i was wondering how it might be possible to implement without using defines.
Since I cant compile the code (i don't have any mutex/multithreading libs currently installed) i'll just look at the code and think it out.
It seems like one can completely implement PROTECTED_WITH by inheriting a template class. The problem is now PROTECTED_MEMBER. It uses a name with ## to create a variable. This isnt much of a problem because we create a class which holds the variable with the () operator to make it appear as a function. However accessing is_held() the problem as i would like not to pass this or mut_ in.
My gut says with out of the box thinking its possible to solve this without defines and without passing in to each variable a this, function ptr or reference. I'll allow everyone to cheat and use c++0x features.
template<typename Mutex>
class TestableMutex {
public:
void lock() { m.lock(); id = this_thread::get_id(); }
void unlock() { id = 0; m.unlock(); }
bool try_lock() { bool b = m.try_lock();
if( b ) id = this_thread::get_id();
return b; }
bool is_held() { return id == this_thread::get_id(); }
private:
Mutex m;
atomic<thread::id> id;
// for recursive mutexes, add a count
};
#define PROTECTED_WITH(MutType) \
public: void lock() { mut_.lock(); } \
public: bool try_lock() { return mut_.try_lock(); } \
public: void unlock() { mut_.unlock(); } \
private: TestableMutex<MutType> mut_;
#define PROTECTED_MEMBER(Type,name) \
public: Type& name() { assert(mut_.is_held()); return name##_; } \
private: Type name##_;
struct MyData {
PROTECTED_WITH( some_mutex_type );
PROTECTED_MEMBER( vector<int>, v );
PROTECTED_MEMBER( Widget*, w );
};
You can use an explicit specialization containing using declarations to list the objects protected by the mutex. Then use a base class to "pass" the access out to the user via operator->, so object->member (with object not being a pointer) performs the mutex assertion.
This is easier done than said:
// Imagine that the members of this class must be locked by the mutex.
class a : public expose_locked_by_arrow< a > {
protected:
int i;
void f();
};
// Declare which members are conditionally locked. Pretty simple and idiomatic.
template<>
struct member_expose< a > : a {
using a::i;
using a::f;
};
#include <iostream>
// Access mutex-locked members with ->
int main() {
a x;
x->i = 5;
a const y( x );
std::cout << y->i << '\n';
}
The library code:
// This template is specialized for each mutex protection client.
template< class >
struct member_expose;
// Base class provides mutex; parameter is derived class (CRTP).
template< class c >
struct expose_locked_by_arrow {
member_expose< c > *
operator->() {
assert ( expose_lock_mutex.is_held() );
return static_cast< member_expose< c > * >( this );
}
member_expose< c > const *
operator->() const {
assert ( expose_lock_mutex.is_held() );
return static_cast< member_expose< c > const * >( this );
}
expose_locked_by_arrow( mutex const &m = mutex() )
: expose_lock_mutex( m ) {}
protected:
mutex expose_lock_mutex;
};
See it run.
The #defines aren't providing any protection as such, rather they are just reducing the amount of typing you'd have to do (in turn, they make sure all the "protected" members have the proper code in place).
There isn't a way that I am aware of to avoid having to put the checks into each getter function - and locking the whole object, as they are returning references to data stored within the protected object.
If however, they could all be returned by value (or not returning anything at all), then you could use a container that locks everything using a proxy object, something like the following (this could probably be done better, i've just quickly hacked it together):
#include <iostream>
struct Mutex
{
void lock()
{
std::cout << "Mutex::lock" << std::endl;
}
void unlock()
{
std::cout << "Mutex::unlock" << std::endl;
}
};
template <class Object>
class ThreadSafeObject
{
mutable Mutex d_mutex;
Object d_object;
public:
struct Proxy
{
mutable Mutex *d_mutex;
Object *d_object;
Proxy(Mutex *mutex, Object *object)
: d_mutex(mutex)
, d_object(object)
{
d_mutex->lock();
}
Proxy(const Proxy& proxy)
: d_mutex(proxy.d_mutex)
, d_object(proxy.d_object)
{
proxy.d_mutex = NULL;
}
~Proxy()
{
if (d_mutex)
{
d_mutex->unlock();
}
}
Object *operator->()
{
return d_object;
}
};
struct ConstProxy
{
mutable Mutex *d_mutex;
const Object *d_object;
ConstProxy(Mutex *mutex, const Object *object)
: d_mutex(mutex)
, d_object(object)
{
d_mutex->lock();
}
ConstProxy(const ConstProxy& proxy)
: d_mutex(proxy.d_mutex)
, d_object(proxy.d_object)
{
proxy.d_mutex = NULL;
}
~ConstProxy()
{
if (d_mutex)
{
d_mutex->unlock();
}
}
const Object *operator->() const
{
return d_object;
}
};
Proxy operator->()
{
return Proxy(&d_mutex, &d_object);
}
ConstProxy operator->() const
{
return ConstProxy(&d_mutex, &d_object);
}
};
struct Foo
{
void foo()
{
std::cout << "Foo::foo" << std::endl;
}
};
int main()
{
ThreadSafeObject<Foo> myFoo;
myFoo->foo();
return 0;
}
Which uses the operator->() trick (when operator-> doesnt reutrn a pointer type, the compiler will keep calling operator-> on the returned values until eventually a regular pointer type is returned) and gives the following output:
Mutex::lock
Foo::foo
Mutex::unlock
Generally speaking though, an object that needs to be used by multiple threads shouldn't be exposing its internals like that, it would be safer to have it accept parameters and use its internal values to act on them.