使用 -O 标志编译时套接字代码失败

Socket code fails when compiled with -O flag

我在 Ubuntu 16.04 上使用 gcc 5.4.0 版。我有一个相当简单的 C 套接字示例,当我使用优化 (-O) 进行编译时它失败了(它在没有优化的情况下工作)。我将原始代码修剪为:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>

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 timeout);

The caller should specify the number of items in the fds array in nfds.

所以,你的 poll(&fds, -1, -1) 应该是 poll(&fds, 1, -1)

编辑:
您还应该检查函数调用的 return 值。
他们可能 return 一个指示错误的值(主要是 -1)并设置 errno.