简体   繁体   English

为什么此托管对象导致段错误?

[英]Why does this hostent cause a segfault?

struct hostent *hostName;

struct in_addr ipv4addr;

inet_pton(AF_INET, inet_ntoa(client.sin_addr), &ipv4addr);

hostName = gethostbyaddr(&ipv4addr, sizeof(ipv4addr), AF_INET);

printf("Host name: %s\n", hostName->h_name);

It segfaults on the last line. 它在最后一行出现段错误。 I looked up proper use of hostent, and the msdn docs show it being used EXACTLY like this. 我查找了hostent的正确使用方法,而msdn文档显示它确实像这样被使用。 What would cause the segfault? 什么会导致段错误?

The gethostbyaddr() function returns NULL in the case of an error, and I don't see you checking for that in your code. 如果发生错误, gethostbyaddr()函数将返回NULL ,但我看不到您在代码中进行检查。 Attempting to dereference a NULL pointer would cause a segfault. 尝试取消引用NULL指针将导致段错误。

You need something like: 您需要类似:

if (hostName == NULL) {
  printf("There was an error!\n");
  exit(1);
}

You may be able to use the herror() function to print out the actual error encountered by the resolver (although the man page indicates that herror() is obsolete). 您可能可以使用herror()函数打印出解析程序遇到的实际错误(尽管手册页指出herror()已过时)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM