【发布时间】:2016-03-28 10:41:39
【问题描述】:
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
int main(int argc, char** argv)
{
char *ptr, **pptr;
char str[100];
struct hostent *hptr;
int i=0;
while(--argc>0)
{
ptr=*(++argv);
if((hptr=gethostbyname(ptr))==NULL)
{
printf("gethostbyname() error for host: %s: %s", ptr, hstrerror(h_errno));
exit(1);
continue;
}
printf("official hostanme: %s \n", hptr->h_name);
for(pptr=hptr->h_aliases; *pptr!=NULL; pptr++)
printf("\talias: %s \n", *pptr);
switch(hptr->h_addrtype)
{
case AF_INET:
pptr=hptr->h_addr_list;
for(; *pptr!=NULL; pptr++)
printf("\taddress: %s \n", inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)));
break;
default:
printf("unknown addres type");
break;
}
}
exit(0);
}
为什么这段代码会出现分段错误?
直到正式名称的输出,都可以。但在那之后,它给了我一个错误。
我认为这个源代码没有语法问题。那有什么问题呢?
【问题讨论】:
-
您正在检查
h_aliases指向的任何char*指针是否为非NULL。但是,h_aliases本身也可能为 NULL(即那里没有别名) - 而您没有检查这一点。 -
您想在调试器中运行代码以找到程序崩溃的确切代码行,然后检查所有涉及的变量以了解实际情况。
-
@tofro: 如果
h_aliases是NULLgethostbyname()坏了。 -
你是用
-Wall -Werror编译的吗?
标签: c unix networking