سؤال

class declarations

struct cmp_str
{
 bool operator()(char const *a, char const *b)
 {
    return std::strcmp(a, b) < 0;
 }
};

class event_t {
public:
  event_t(String *_session_time, String *_event_type, String *_table_name, String *_num_of_events);
  ~event_t();
   char *table_name;
   char *event_type;  
   pthread_mutex_t lock;
   pthread_cond_t cond;
   int num_of_events_threshold;
   double time_out; 
   int num_of_events_so_far; 
};  
std::map <char*, std::list<event_t*>, cmp_str > all_events;  //global map

I have this function which waits for a variable to reach for a certain threshold which is done through pthread_cond and pthread_mutex. It then returns. The last line gives segmentation fault.

void foo(){
    //don't worry event object ic created properly
    event_t *new_event = new event_t(args[0]->val_str(s),(args[1]->val_str(s)), (args[2]->val_str(s)), (args[3]->val_str(s)));

    map<char*, list<event_t*> >::iterator map_it;  
    map_it = all_events.find(new_event->table_name);

    if(map_it == all_events.end()){
      list<event_t*> *my_list = new list<event_t*>();
      my_list->push_back(new_event);
      all_events[new_event->table_name] = *my_list;
    }
    else{
      map_it->second.push_back(new_event);
      for (list<event_t*>::iterator list_it=map_it->second.begin(); list_it!=map_it->second.end(); ++list_it)
        std::cout << (*list_it)->event_type << " " << (*list_it)->time_out << " " << (*list_it)->num_of_events_threshold << '\n';
    }


/*
* waiting for number of events reach its threshold.
*/
    pthread_mutex_lock(&new_event->lock);

    while(new_event->num_of_events_so_far < new_event->num_of_events_threshold )
      pthread_cond_wait(&new_event->cond, &new_event->lock);
    pthread_mutex_unlock(&new_event->lock);
    // segmentation fault!!!
    for (list<event_t*>::iterator list_it=map_it->second.begin(); list_it!=map_it->second.end(); ++list_it)
        std::cout << (*list_it)->event_type << " " << (*list_it)->time_out << " " << (*list_it)->num_of_events_threshold << '\n';
}   
هل كانت مفيدة؟

المحلول

if(map_it == all_events.end()){
  list<event_t*> *my_list = new list<event_t*>();
  my_list->push_back(new_event);
  all_events[new_event->table_name] = *my_list;
}

This code doesn't leave map_it pointing to a valid iterator, so when you dereference it at the bottom of the function it will crash.

You probably want to add a line like

map_it = all_events.find(new_event->table_name);

inside the if { } clause.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top