Segmentation fault 11 in MacOS X- C++ [migrated]
- by Marcos Cesar Vargas Magana
all. 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.