gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:47:29 25 4
gpt4 key购买 nike

我在 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)

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

关于c - 使用 -O 标志编译时套接字代码失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57271852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com