VSN
VSN

Reputation: 416

Using the void ptr in the events structure for epoll

There is a void pointer in the epoll event structure. I am malloc-ing memory for this and using it elsewhere. Now when I want to take the FD off the epoll list, will this pointer be freed by itself? (A logical thought chain would be that the event structure is maintained internally, possibly by the kernel. So it would free the event strucutre and the memory allocated to the pointer too) Or would I have to free it explicitly?

P.S. I saw a piece of code that does not free the memory allocated to the pointer. I feel that it should be freed explicitly.

Upvotes: 2

Views: 986

Answers (2)

Adam Rosenfield
Adam Rosenfield

Reputation: 400304

No, the pointer will not be freed by itself. As far as the kernel is concerned, it's just an opaque value which it doesn't know how to deal with. It doesn't know if it's a pointer into the stack, heap, data segment, or something else entirely. So it couldn't possibly know that it should free() it.

The basic rule is, unless the documentation explicitly says otherwise, you are responsible for freeing any memory you malloc. So, when you remove a file descriptor from an epoll list, you also need to free the corresponding pointer you malloced.

Upvotes: 4

Francis Upton IV
Francis Upton IV

Reputation: 19443

I have not used epoll before, but I think a very strong argument for that you have to free is is that the epoll_data is a union, so there is no way that any other code can be able to free whatever the pointer points to.

Upvotes: 2

Related Questions