Eric
Eric

Reputation: 1697

pointer to std::map trouble

Please consider the following code where I get an access violation inserting values into a std::map object. Not sure why. The code as you see it uses

std::map<int, int>

however, I initially tried

std::map<int, MSGTYPE>

with the same resulting access violation. (I know enums are INTs).

// a common include file has this
// common.h

enum MSGTYPE
{
  MSG_R1,
  MSG_A1,
  MSG_L1,
  MSG_S1,
  MSG_S2
};

typedef std::map<int, int> SYSMsgMap;

typedef struct _MYOBJ
{
  int x1;
  int x2;
  SYSMsgMap XFerMap;
}MYOBJ;

My use of these structures looks like so:

MYOBJ *cMYOBJ::AddNetwork(cvnet *net)
{
MYOBJ *ob;

  ob = new MYOBJ();

  // initialization code removed for this post/brevity

  BuildMsgMap(ob->XFerMap);

  // rest removed for this post/brevity
}

void cMYOBJ::BuildMsgMap(std::map<int, int> &mm)
{

  mm.clear();

  switch(NETTYPE)
  {
    case 1: 
      mm[ 1] = MSG_R1;  <-- Access violation here!
      mm[ 2] = MSG_A1;
      mm[ 4] = MSG_L1;
      mm[16] = MSG_S1;
      mm[32] = MSG_S2;
    break;

 // rest removed...
}

Upvotes: 1

Views: 573

Answers (3)

Krzysztof Kosiński
Krzysztof Kosiński

Reputation: 4325

I think you are getting an access violation because MYOBJ has no constructor defined, and therefore the constructor of SYSMsgMap is not getting called. Add an empty no-argument constructor to MYOBJ and see if it changes things, e.g.

typedef struct _MYOBJ
{
  _MYOBJ() {}
  int x1;
  int x2;
  SYSMsgMap XFerMap;
}MYOBJ;

Upvotes: 0

A. K.
A. K.

Reputation: 38116

i think since mm is a reference to the mm[0], and that is all the memory allocation you've got so for mm[1] you need to do an insert.

or you'd like to do

ob = new MYOBJ[33];//since you have indexed mm[32] in the next function

hope this helps

Upvotes: 0

vines
vines

Reputation: 5225

Doesn't ob get accidentally cleared with memset(ob, sizeof(MYOBJ), 0) somewhere after ob = new MYOBJ; and before the call to BuildMsgMap()?

(Since the code is legacy and since memset trick is often used in C.)

Upvotes: 2

Related Questions