libevent: is it allowed to free an event inside its callback function if the event is created by malloc

霸气de小男生 提交于 2019-12-24 13:37:21

问题


I need to create events using malloc, but I'm at a loss where to free them, I'm wondering whether it is allowed to free an event inside its callback function, like:

struct event *pkt_ev = (struct event *)malloc(sizeof(struct event));
evtimer_set(&pkt_ev, timer_cb, &pkt_ev);    
event_base_set(base, &pkt_ev); 
event_add(&pkt_ev, timeout);

the callback function timer_cb():

    timer_cb(int fd, short ev, void* arg){
    .......
    free(arg);    // here the arg is &pkt_ev
}

my initial thinking is: after the callback function timer_cb() is called, the libevent will implicitly call event_del(&pkt_ev). But since I freed &pkt_ev inside the callback, there will be a crash/exception on event_del(&pkt_ev). is it right?

however, if event_del(&pkt_ev) doesn't care what content pkt_ev points to, it might not be a problem?

besides, in this function:

        event_add(struct event *ev, struct timeval *timeout);

the content pointed by ev should be cared a lot, generally it should be a global variable or its lifetime should cover the event loop(namely, when the event loop function is running, it will access the content pointed by ev). How about the content pointed by timeout? should the content pointed by timeout cover the event loop?


回答1:


You first assumption is wrong, libevent implicitly calls event_del() before invoking the callback function, not after (given that the EV_PERSIST flag isn't set). So there is no issue freeing pkt_ev in a callback if the EV_PERSIST flag is not set. If it is set, you need to explicitely call event_del() first.

Regarding your second question, no, the content pointed by timeout is copied before event_add() returns.



来源:https://stackoverflow.com/questions/16691188/libevent-is-it-allowed-to-free-an-event-inside-its-callback-function-if-the-eve

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!