出于某种原因 valgrind
不断抛出以下错误:
==6263== Invalid read of size 4
==6263== at 0x40151B9: (within /lib/ld-2.7.so)
==6263== by 0x4005C29: (within /lib/ld-2.7.so)
==6263== by 0x4007A47: (within /lib/ld-2.7.so)
==6263== by 0x40114F3: (within /lib/ld-2.7.so)
==6263== by 0x400D585: (within /lib/ld-2.7.so)
==6263== by 0x4010F0D: (within /lib/ld-2.7.so)
==6263== by 0x4141391: (within /lib/tls/i686/cmov/libc-2.7.so)
==6263== by 0x400D585: (within /lib/ld-2.7.so)
==6263== by 0x4141554: __libc_dlopen_mode (in /lib/tls/i686/cmov/libc-2.7.so)
==6263== by 0x411B286: __nss_lookup_function (in /lib/tls/i686/cmov/libc-2.7.so)
==6263== by 0x411B39F: (within /lib/tls/i686/cmov/libc-2.7.so)
==6263== by 0x411CFC5: __nss_hosts_lookup (in /lib/tls/i686/cmov/libc-2.7.so)
==6263== Address 0x4183d24 is 36 bytes inside a block of size 37 alloc'd
==6263== at 0x4022AB8: malloc (vg_replace_malloc.c:207)
这是我的做法。发生这种情况的任何原因?谢谢
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
char *IPtoHostname(const char *ipaddress)
{
struct hostent *host;
unsigned int ip = 0;
ip = inet_addr (ipaddress);
host = gethostbyaddr ((char *) &ip, sizeof (unsigned int), AF_INET);
if (host == NULL) return NULL;
return strdup(host->h_name);
}
int main () {
const char *ip = "65.55.4.170";
char *a = NULL;
a = IPtoHostname(ip);
printf ("%s\n", a);
free (a);
return 0;
}
更新:当我在 Linux hardy 2.6.24-16-generic
下运行时会发生它在 Ubuntu 9.10
下不会发生/p>
最佳答案
你的代码没问题(虽然你真的应该使用 in_addr_t
而不是 unsigned int
作为 IPtoHostname 中的变量
).ip
( )
Valgrind 报告是 well-known issue - 误报或 glibc 中的错误。
关于C-gethostbyaddr & Valgrind,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4309103/