我正在使用gcc版本5.4.0的Ubuntu 16.04。我在C中有一个相当简单的套接字示例,当我使用优化(-O)进行编译时,该示例失败了(它没有进行优化)。我将原始代码修剪为:
#include#include #include #include #include #include #include #include #include int main() { struct addrinfo *ai, hints; memset(&hints, 0, sizeof hints); getaddrinfo(NULL, "7471", &hints, &ai); int listen_fd = socket(ai->ai_family, SOCK_STREAM, 0); bind(listen_fd, ai->ai_addr, ai->ai_addrlen); freeaddrinfo(ai); listen(listen_fd, 128); struct pollfd fds; fds.fd = listen_fd; fds.events = POLLIN; poll(&fds, -1, -1); }
编译器在调用poll()时遇到问题。警告消息是
in function ‘poll’, inlined from ‘main’ at simplecode.c:25:5: /usr/include/x86_64-linux-gnu/bits/poll2.h:43:9: warning: call to ‘__poll_chk_warn’ declared with attribute warning: poll called with fds buffer too small file nfds entries return __poll_chk_warn (__fds, __nfds, __timeout, __bos (__fds));
实际的运行时错误会更长,但开头为:
*** buffer overflow detected ***: ./simplecode terminated
有任何想法吗?
从 man 2 poll
int poll(struct pollfd * fds,nfds_t nfds,int超时);
调用者应在nfds中指定fds数组中的项目数。
所以,你poll(&fds, -1, -1)
应该poll(&fds, 1, -1)
编辑:
您还应该检查函数调用的返回值。
他们可能会返回一个指示错误的值(主要是-1
)并设置errno。