简体   繁体   English

std :: list迭代器中的分段错误

[英]segmentation fault in iterator of std::list

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. 我有这个函数,它等待变量达到某个阈值,这是通过pthread_cond和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. 此代码不会使map_it指向有效的迭代器,因此在函数底部取消引用时,它将崩溃。

You probably want to add a line like 您可能想添加一行

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

inside the if { } clause. if { }子句中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM