Search code examples
c++memoryvectorcorruption

C++ vector memory access issue


I have a vector with a list of commands as shown below:

//COMMAND INITIALISATION
 std::vector<std::string> objectInitialisationAction;
 objectInitialisationAction.push_back("CREATE");              //0
 objectInitialisationAction.push_back("END_CREATE");          //1       
 objectInitialisationAction.push_back("START_TIMELINE");      //2

I only access this vector by using my function shown below:

int SearchFor(std::string search, std::vector<std::string> from)
{
int result=-1;
for(int i=0; i<from.size(); i++)
if(from[i]==search)
{
     result=i;
     break;
}
if(result == -1)
{
   std::ofstream error("searching.txt");
   error<<"search failed, original value = \""<<search<<"\""<<std::endl;
   error<<"values in the table:"<<std::endl;
   for(int i=0; i<from.size();i++)
   error<<"value "<<i<<": "<<from[i]<<std::endl;
   error.close();
}

return result;
}

With only one function call:

commandNum=SearchFor(command[0], objectInitialisationAction);

This is the only place where I access the vector, yet when I call the function for the nth time (it always brakes at the same point in the code) it accesses wrong and outputs gibberish. Some of the code I list below:

    search failed, original value = "CREATE"
    values in the table:
    value 0: CREATE      Øç¼   Œ                      Ôç¼   Œ                      Ðç¼              Exit               ¼ç¼          ¸ç¼   Œ      p«üxðù   ;    ´ç¼   Œ      pëù@òø  €<    °ç¼   ŒBerlin Sans FB Demi e   ¬ç¼   ˆ°¿^nmra     œç¼   ŒBerlin Sans FB Demi e   ˜ç¼             help        ”ç¼   ˆ          object_dump ç¼             test        Œç¼   Ž          spawn       ˆç¼   ‹          load_map    „ç¼   Ž
//and so on...   

Any suggestions as to why a vector may corrupt like that?


Solution

  • Your code looks correct to me. In this case, there should be another part of your application that corrupts the memory. For example, there could be an out-of-range array access, a dangling pointer or a use-after-delete somewhere. Tools like Valgrind might help you here.