1

I have a function which creates an array of Maps:

map<string, int> *pMap

And a function which writes maps to the array:

int iAddMap(map<string, int> mapToAdd, map<string, int> *m, int i)
{
    m = &(pMap[i]);
    memcpy(m, mapToAdd, sizeof(map<string, int>));
}

And a function to get maps from the array

map<string, int>& getMap(int i)
{
    return pMap[i];
}

I can write maps to the array without any issue, but every get call results in a seg fault:

int val; 
// val defined after this
map<string, int> * pGetMap = &(getMap(val));

Any suggestions on why this is happening?

donalmg
  • 627
  • 5
  • 15
  • 22
  • 1
    why not use a vector of maps? – NG. Apr 29 '10 at 12:13
  • 3
    "Any suggestions on why this is happening?" Yep. You urgently need to pick up a basic C++ book and read that thoroughly. There's no much wrong with your code, I wouldn't know where to start. See here: http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list. – sbi Apr 29 '10 at 12:16

3 Answers3

8

You cannot use memcpy() to copy objects like maps, or indeed any other kind of C++ container - you need to use assignment, which takes into account the map's underlying structure and se,mantics. And you should be using a vector <map>, as you actually seem to want a copy rather than a pointer.

4

Never ever use memcpy for copying an object of a map (or whatever class, for that matter) - use assignment or copy constructor instead. memcpy is a C function, which has no idea of the internal structure of a C++ object, so it is almost guaranteed to mess things up.

Also you would better use an std::vector<map<string, int> > instead of an array:

std::vector<map<string, int> > maps;

void addMap(const map<string, int>& mapToAdd, int i)
{
    maps[i] = mapToAdd;
}

map<string, int>& getMap(int i)
{
    return maps[i];
}

Note: addMap does not return anything in your example code, so I changed its return type to void. Also I pass mapToAdd as const reference rather than by value.

Péter Török
  • 114,404
  • 31
  • 268
  • 329
3

This seems like an unholy mix of C and C++ programming, begin with changing:

memcpy(m, mapToAdd, sizeof(map<string, int>));

to

*m = *mapToAdd;

Also in the function

int iAddMap(map<string, int> mapToAdd, map<string, int> *m, int i)

What is the purpose of m? Any modifications to m won't be seen outside of this function.

Andreas Brinck
  • 51,293
  • 14
  • 84
  • 114
  • You probably meant *m = *mapToAdd; – nothrow Apr 29 '10 at 12:16
  • this will set the vector to the same address. and you probably meant &mapToAdd (address-of operator and not dereference operator) – knittl Apr 29 '10 at 12:17
  • @knittl What vector? Both `m` and `mapToAdd` are pointers to `std::map` so doing `*m = *mapToAdd` will assign the map `mapToAdd` is pointing at to the map `m` is pointing at. – Andreas Brinck Apr 29 '10 at 12:20