Function works when passed string literal, but not a variable

I'm making a .json loader for a project that I'm working on, and to simplify things, I decided to make all the root attributes named in a separate file. Here's my problem: my loading function, Add(const char* id), works just fine when I pass it a string literal. However, when I use a function that iterates through a vector list, even with the exact same definitions as the literal, it returns the error:
std::out_of_range at memory location 0x0026fb30
I cannot, for my life and love of it, figure out what is going wrong. I've stepped through it with the VS2010 debugger about a hundred times, checked against memory locations, and just have done everything I can think of, all to no avail. If anybody can offer some insight, it would be greatly appreciated.

The code, with data-checking omitted:

The std::map I'm adding to:
 
static std::map<const char*, Item*> *s_mItems;

Initialized as std::map<const char*, Item*> *Item::s_mItems;

Add() Function (Works by itself with a literal):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
static bool Add(const char* id)
{
    ...
    std::string name = node.Get("name").ToString();
    std::string desc = node.Get("description").ToString();
    int rarity = StrToRarity(node.Get("rarity").ToString());
    int price = node.Get("price").ToInt();

    Item *_temp = new Item(name.c_str(), desc.c_str(), rarity, price);
    std::pair<const char*, Item*> temp(id, _temp);
    s_mItems->insert(temp);
    printf("[INFO] Added item '%s' with id '%s'.\n", name.c_str(), id);
    ...
}


AddList() function, where the program always breaks:
1
2
3
4
5
6
7
static void AddList(std::vector<std::string> list)
{
    for(std::vector<std::string>::iterator it = list.begin(); it != list.end(); it++)
    {
	    Add(it->c_str());
    }
}
Last edited on
You could use the element access operator for the vector instead of an iterator. That would simplify some things. Are any of the strings in the vector blank?
The list vector is local to the AddList function so it will be destructed at the end of the function, leaving all pointers returned by it->c_str() invalid.

Note that using const char* as a map key will compare pointers, and will treat two different pointers as different keys even if they point to strings that are equal.

Have you considered using std::string instead of const char* everywhere? I think it would make things much easier for you.
Last edited on
Thanks Peter87, I changed the const char*s to std::strings, and it worked. Pointers have always been a pain for me, I've just never had trouble with const char* maps before.
Topic archived. No new replies allowed.