开发者

What's the reason of this segmentation fault?

It doesn't happen always,but will happen when the server application has been running for quite a while.

What's the reason and how can I fix it?

Code as follows:

struct hostent*     Host;
Result->sin_family=AF_INET;
Result->sin_port=htons((unsigned short)Port);

Host=gethostbyname(HostName);

if(!Host)
{
    unsigned long int addr=inet_addr(HostName);
    if(addr!=-1)
        Host=gethostbyaddr(&addr,sizeof(addr),AF_INET);

    if(!Host)
    {
        if(errno!=ETIMEDOUT)
            errno=-1; /* use h_errno */
        printf("Unknown host for server [%s].", HostName);
        return(0);
    }
}

memcpy((char*)&Resul开发者_如何学Ct->sin_addr,(char*)Host->h_addr,sizeof(Result->sin_addr));

core dump:

#0  0x0000000000401913 in proxy_getaddr (HostName=0x7ae30be0 "stackoverflow.com", Port=80, Result=0x7ae30bd0) at proxy.c:529

529     memcpy((char*)&Result->sin_addr,(char*)Host->h_addr,sizeof(Result->sin_addr));
(gdb) p *Host
$4 = {h_name = 0xc4ee048 "", h_aliases = 0xc4ee030, h_addrtype = 2, h_length = 4, h_addr_list = 0xc4ee038}
(gdb) print Result 
$5 = (struct sockaddr_in *) 0x7ae30bd0
(gdb) print *Result 
$6 = {sin_family = 2, sin_port = 20480, sin_addr = {s_addr = 0}, sin_zero = "\000\000\000\000\000\000\000"}



(gdb) p Host->h_addr_list[0]
$1 = 0x0
(gdb) p Host->h_addr_list
$2 = (char **) 0x1bd9d050


Given that the Host and Result variables both point to legitimate blocks of memory, the most likely cause is that Host->h_addr is NULL. This would be the case if the list of addresses returned by gethostbyname() or gethostbyaddr() were empty.

I don't know how that could be caused (the documentation on my OS X system implies that both functions should return NULL if no addresses can be found). However, I would check Host->h_addr_list[0] in the debugger to confirm.

Edit

The update of the debug info shows where the problem is: Host->h_addr is NULL. h_addr is actually a #define like this:

#define h_addr h_addr_list[0]

One of the functions is returning a struct hostent with an empty address list.


Maybe, source and destination memory areas overlap? i.e.

&Result->sin_addr >= Host->h_addr >= &Result->sin_addr + sizeof(Result->sin_addr)


The memcpy is failing.

This could be caused by (1) sin_addr and h_addr are not the same sizes or (2) sin_addr is a pointer and you have not malloc'd memory for it.

Please provide the definition and initialisation of Result for more info.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜