Reputation: 31
I have a "segmentation fault 11" error when I run the following code. The code actually compiles but I get the error at run time.
//** Terror.h **
#include <iostream>
#include <string>
#include <map>
using std::map;
using std::pair;
using std::string;
template<typename Tsize>
class Terror
{
public:
//Inserts a message in the map.
static Tsize insertMessage(const string& message)
{
mErrorMessages.insert( pair<Tsize, string>(mErrorMessages.size()+1, message) );
return mErrorMessages.size();
}
private:
static map<Tsize, string> mErrorMessages;
};
template<typename Tsize>
map<Tsize,string> Terror<Tsize>::mErrorMessages;
//** error.h **
#include <iostream>
#include "Terror.h"
typedef unsigned short errorType;
typedef Terror<errorType> error;
errorType memoryAllocationError=error::insertMessage("ERROR: out of memory.");
//** main.cpp **
#include <iostream>
#include "error.h"
using namespace std;
int main()
{
try
{
throw error(memoryAllocationError);
}
catch(error& err)
{
}
}
I have kind of debugging the code and the error happens when the message is being inserted in the static map member. An observation is that if I put the line:
errorType memoryAllocationError=error::insertMessage("ERROR: out of memory.");
inside the "main()" function instead of at global scope, then everything works fine. But I would like to extend the error messages at global scope, not at local scope. The map is defined static so that all instances of "error" share the same error codes and messages. Do you know how can I get this or something similar.
Thank you very much.
Upvotes: 0
Views: 1960
Reputation: 599
I had the same issue when I tried to run on Mac OS X 10.7 an application I compiled for OS X 10.8.
Setting the target to 10.7 solved the problem. The application runs fine on both 10.7 and 10.8 OS X environments.
Upvotes: 2
Reputation: 182819
You need to ensure that the constructor for mErrorMessages
runs before you use it by calling insertMessage
. You can do this any way you want, but you must do it somehow.
Upvotes: 0