gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 19:29:20 28 4
gpt4 key购买 nike

我尝试使用 official getifaddrs page 中的示例在 Ubuntu 18.04.5 LTS 仿生(Odroid-N2 board ARM64)上出现段错误。
进一步分析表明,由 getifaddrs() 填充的 struct 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: %s\n",ifa->ifa_name);
printf("\tThis: %p\n", ifa);
printf("\tNext: %p\n", ifa->ifa_next);
printf("\tFlags: %x\n",ifa->ifa_flags);
printf("\tAddr: %p\n", ifa->ifa_addr);
printf("\tMask: %p\n", ifa->ifa_netmask);
printf("\tDst: %p\n", ifa->ifa_dstaddr);
printf("\tData: %p\n", 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_addr 的指针是 0x49f83b800000000,它被报告为“未堆栈、malloc 或(最近)释放”
有人遇到同样的问题吗?
谢谢

最佳答案

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

关于c - getifaddrs() 函数处理结果导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68146104/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com