gpt4 book ai didi

c++ - std::list 的迭代器中的段错误

转载 作者:行者123 更新时间:2023-11-28 07:30:35 24 4
gpt4 key购买 nike

类声明

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

我有这个函数等待变量达到某个阈值,这是通过 pthread_cond 和 pthread_mutex 完成的。然后返回。最后一行给出了段错误。

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;
}

这段代码不会让 map_it 指向一个有效的迭代器,所以当你在函数底部取消引用它时它会崩溃。

你可能想添加一行

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

if { } 子句中。

关于c++ - std::list 的迭代器中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17821139/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com