I have declared a std::map in .h file
#include "pl.h"
#include <conio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <vector>
#include <map>
using namespace std;
class ReadingXDSLfile
{
public:
ReadingXDSLfile();
~ReadingXDSLfile();
void readDotXDSLFile(string fileName, ifstream &file);
void writeNodesList();
protected:
typedef std::map<std::string, int> nodesMap;
nodesMap nodes;
std::vector<string> nodesName;
std::map<std::string, int>::iterator nodeItr, nodeItr1;
string outFileName;
private:
};
and in .cpp file when i try to insert an item using following line of code then it gives access violation error
int counter=0;
string strNode;
...
....
....
std::pair<string, int>prNode (strNode, counter);
nodes.insert(prNode);
error:
Unhandled exception at 0x0043c5d9 in testMMHC.exe: 0xC0000005: Access violation reading location 0x0000002c.
Now i declared a temp map variable in the function (.cpp file), it allows me to insert. But when i copy temp map to the global map declared in the header file then it goes in infinite loop and never exit.
It happens with all map variables declared in header file.
First, declaring a typedef for your map in your header is fine, but don't declare the variable itself unless you use extern
. There should be only one, and it should be in your .cpp file.
In .h file:
#include <map>
#include <string>
typedef std::map<std::string, int> NodeMap;
extern NodeMap nodes;
Next, your .cpp file:
NodeMap nodes;
And lastly, regarding insertion, you have a plethora of possible ways to do it.
std::string strIndex = "foo";
int value = 0
// one way.
nodes[strIndex] = value;
// another way
nodes.insert(NodeMap::value_type(strIndex,value));
to show a few examples.
EDIT: The OP has changed the source content of the question and now shows that nodes
is not a global, but rather is a member variable of another class. Everything about extern
in this answer just became moot.
The offset of the violation indicates that one of the iterators or the class itself is being referenced through a null pointer. 0x2C is 44-bytes deep off NULL, whiuch indicates to me that the ReadingXDSLfile
object being referenced is likely coming from a NULL pointer.
Without more information from the OP about how the referenced object is being allocated and accessed, I'm afaid I can't offer up much more than a well-defined tutorial on how to extern a variable in a header, which should be evident has nothing to do with this problem.
User contributions licensed under CC BY-SA 3.0