Search code examples
c++vectorcastingcallbackvoid-pointers

problem casting a void* to a (vector<void*>*)


I am currently working on a complex logic, where I have a map<string,void*> with these value:

string mystring[10] = {"key1","key2","keyN"};
for(string s: mystrings){
    vector<void*> v;
    v.push_back(this);
    v.push_back(&s);
    map.insert({s,&v});
}

At a certain point, I have to pass my vector to a timer which triggers a callback:

mytimer(int milliseconds, mycallback,void* (parameter of the callback));
this->mytimer(1000,MY_CALLBACK,map.at("Key1"));

The problem is in the callback:

static void MY_CALLBACK(void*);
void MY_CALLBACK(void* args){
    auto obj = (vector<void*>*) args;
    auto key = (string*) obj->at(1);
    auto logic = (MY_CLASS *) obj->at(0);
    some logic;
}

The program crashes because of an "out of range" error when I try to get any value of the vector.

What is the problem?


Solution

  • Here

    for(string s: mystrings){
         vector<void*> v;
         v.push_back(this);
         v.push_back(&s);
         map.insert({s,&v});
       }
    

    You are inserting a pointer to a vector whose lifetime ends at the end of the iteration. The pointer in the map is useless. Its a dangling pointer. Later dereferencing the pointer leads to undefined behavior.