gpt4 book ai didi

c - 段错误(核心转储)

转载 作者:行者123 更新时间:2023-11-30 21:05:45 24 4
gpt4 key购买 nike

当我执行以下代码时,我收到段错误(核心转储)。

我很难确定为什么会出现此错误。我认为这是一个指针问题。

这是代码

struct info{
char *host;
char *channel;
char *user;
}Ainfo;


int main(int argc, char *argv[])
{
struct addrinfo hints;
struct addrinfo *result, *result2;
int sock,getadd;

Ainfo.host=argv[2];

if(argc<3)
{
perror("too few Arguments\n");
exit(0);
}

memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = 0;
hints.ai_protocol = 0;


getadd=getaddrinfo(Ainfo.host,PORT,(struct addrinfo *)&hints,&result);
if(getadd!=0){
perror("\n");
exit(0);
}

return 0;
}

最佳答案

将关键评论转化为答案。

PORT 定义为什么? POSIX 说 getaddrinfo()已有原型(prototype)

int getaddrinfo(const char *restrict nodename, const char *restrict servname,
const struct addrinfo *restrict hints, struct addrinfo **restrict res);

还规定:

The nodename and servname arguments are either null pointers or pointers to null-terminated strings. One or both of these two arguments shall be supplied by the application as a non-null pointer.

OP 注释:

  • 端口设置为 6667 — #define PORT 6667

如果您有#define PORT 6667,那么它看起来既不像空指针,也不像以空结尾的字符串。因此(对我来说)您的代码崩溃并不奇怪。

令人惊讶的是,您没有收到编译器警告,告诉您做错了。启用警告,或者获得更好的编译器。并注意警告——编译器比你更了解 C。我很少运行不能干净编译的代码

gcc -O3 -g -std=c11 -Wall -Wextra -Werror -Wmissing-prototypes -Wstrict-prototypes … 

(-Werror 确保我处理警告,因为如果有警告,编译就会失败!我有时会添加一些更多警告;我很少删除其中任何警告。)

关于c - 段错误(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52908203/

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