tags:

views:

167

answers:

2

In my SDL program, I am using a map construct to simulate an "infinite" array of objects within a certain class. The code manages to compile fine, but when I run the program, as soon as one of the functions using the maps is trigger, the program crashes, returning a value of 3.

So, here's exactly what I'm doing:

class MyClass
{
     public:
           int MyFunction();
     protected:
           std::map< int, MyObject > MyMap;
}

int MyClass::MyFunction()
{
     ...
     int i;

     if( MyMap.empty() )
     {
          i = 1;
     }
     else
     {
         i = MyMap.size() + 1;
     }

     MyMap[ i ] = PreviouslyDefinedObject;

     return i;

}

When MyFunction() is called from a MyClass object, the crash occurs. It seems to happen whenever anything of use is done with MyMap: it crashes if you comment out the penultimate line and just try to return i, and it crashes if you just set i = 1 and then assign an object to MyMap[i]

This is the first time I've ever used a map, so I'm not certain I'm using them right. Is this a basic mistake somewhere? Can anyone point me in the right direction? Cheers.

A: 

Maps are used to associate a key with a value. If you're looking for an array, you should use a vector. It will do a better job of simulating an "infinite array" than a map, because a map isn't an array.

Note you can allocate a lot of elements with a vector, usually. If you're really trying to simulate a large array, I'd recommend wrapping up a vector of vectors. With some math, you could create an operator[] for it that indexes into the correct array, to the correct element.

As for your code, there really isn't enough information to determine why it should be crashing, you'd have to try to create a minimal program for us to compile or look at.

GMan
I'll give this a go, thanks very much.
CJ
+2  A: 

Maybe you are calling the function from an uninitialized pointer, like this:

MyClass *obj;
obj->MyFunction();
sth
...Oops.This is of course exactly what I am doing; forgot a line of code earlier on and haven't initialized obj. Having done that the code works fine. Thanks very much.
CJ
Nice catch, sth.
GMan