出於某種原因valgrind
不斷拋出以下錯誤:C- gethostbyaddr&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
vg_replace_malloc僅存的valgrind – thkala 2010-11-29 23:33:25
你編譯程序用-O0 -g,對不對? – thkala 2010-11-29 23:56:26
@thkala:我編譯時使用了:`gcc -Wall -O0 -g prog.c` – RichardThomson 2010-11-30 00:00:35