libevent: is it allowed to free an event inside it

2019-08-06 21:53发布

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?

标签: c linux libevent
1条回答
贪生不怕死
2楼-- · 2019-08-06 22:21

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.

查看更多
登录 后发表回答