c-getifaddrs()函数的处理结果导致分段错误



我试图在Ubuntu 18.04.5 LTS bionic(Odroid-N2板ARM64(上使用官方getifaddrs页面中的示例,但出现了分段错误。

进一步的分析表明,getifadrs((填充的结构ifaddrs包含无效指针。

这是我的代码:

#include <stdint.h>
#include <unistd.h>
#include <ifaddrs.h>
int main(int argc, char** argv) {
struct ifaddrs *ifaddr;
int family;

if (getifaddrs(&ifaddr) == -1) {
perror("getifaddrs");
return -1;
}


for (struct ifaddrs *ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == NULL)
continue;

printf("IF: %sn",ifa->ifa_name);           
printf("tThis: %pn", ifa);
printf("tNext: %pn", ifa->ifa_next);
printf("tFlags: %xn",ifa->ifa_flags);
printf("tAddr: %pn", ifa->ifa_addr);
printf("tMask: %pn", ifa->ifa_netmask);
printf("tDst: %pn", ifa->ifa_dstaddr);
printf("tData: %pn", ifa->ifa_data);

family = ifa->ifa_addr->sa_family;
}
return 0;   
}

valgrind打印的是:

==18313== Memcheck, a memory error detector
==18313== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==18313== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==18313== Command: ./main.bin
==18313== IF: lo
This: 0x49f8380
Next: 0x49f8438
Flags: 10049
Addr: 0x49f83b800000000
Mask: (nil)
Dst: 0x49f840000000000
Data: 0x49f89f800000000
==18313== Invalid read of size 2
==18313==    at 0x10899C: main (main.c:28)
==18313==  Address 0x49f83b800000000 is not stack'd, malloc'd or (recently) free'd
==18313==
==18313==
==18313== Process terminating with default action of signal 11 (SIGSEGV)
==18313==  Access not within mapped region at address 0x49F83B800000000
==18313==    at 0x10899C: main (main.c:28)
==18313==  If you believe this happened as a result of a stack
==18313==  overflow in your program's main thread (unlikely but
==18313==  possible), you can try to increase the size of the
==18313==  main thread stack using the --main-stacksize= flag.
==18313==  The main thread stack size used in this run was 8388608.
==18313==
==18313== HEAP SUMMARY:
==18313==     in use at exit: 1,944 bytes in 1 blocks
==18313==   total heap usage: 8 allocs, 7 frees, 7,476 bytes allocated
==18313==
==18313== LEAK SUMMARY:
==18313==    definitely lost: 0 bytes in 0 blocks
==18313==    indirectly lost: 0 bytes in 0 blocks
==18313==      possibly lost: 0 bytes in 0 blocks
==18313==    still reachable: 1,944 bytes in 1 blocks
==18313==         suppressed: 0 bytes in 0 blocks
==18313== Rerun with --leak-check=full to see details of leaked memory
==18313==
==18313== For counts of detected and suppressed errors, rerun with: -v
==18313== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0) Segmentation fault

您可以看到ifa_dr的指针是0x49f83b800000000,它被报告为"0";不堆叠’d、malloc’d或(最近(空闲’d";

有人面临同样的问题吗?感谢

显然将-fpack struct=2传递给gcc导致了这个问题

最新更新