我在我的C程序中收到一个奇怪的SIGABRT,这是我出现问题的函数:
int get_interface_mac_addr(Interface* iface) {
char arquivo[10];
sprintf(arquivo, "/sys/class/net/%s/address", iface->interface_name);
int fd;
fd = open(arquivo, O_RDONLY, 0);
char buf[100];
read(fd, buf, sizeof (buf));
buf[strlen(buf) - 1] = '\0';
strcpy(iface->interface_mac_addr, buf);
close(fd);
return GET_MAC_ADDR_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
错误发生在最后一行代码"}".
我尝试使用GDB进行调试,但我是新手,所以我不理解GDB告诉我的很多事情.以下是GDB的输出:
Core was generated by `./vfirewall-monitor'.
Program terminated with signal 6, Aborted.
#0 0x00007f36c043b425 in __GI_raise (sig=<optimized out>) at ../nptl/sysdeps/unix/sysv/linux/raise.c:64
64 ../nptl/sysdeps/unix/sysv/linux/raise.c: No such file or directory.
(gdb) bt
#0 0x00007f36c043b425 in __GI_raise (sig=<optimized out>) at ../nptl/sysdeps/unix/sysv/linux/raise.c:64
#1 0x00007f36c043eb8b in __GI_abort () at abort.c:91
#2 0x00007f36c047939e in __libc_message (do_abort=2, fmt=0x7f36c058157f "*** %s ***: %s terminated\n")
at ../sysdeps/unix/sysv/linux/libc_fatal.c:201
#3 0x00007f36c050ff47 in __GI___fortify_fail (msg=0x7f36c0581567 "stack smashing detected") at fortify_fail.c:32
#4 0x00007f36c050ff10 in __stack_chk_fail () at stack_chk_fail.c:29
#5 0x00000000004029be in get_interface_mac_addr (iface=0x7f36b4004560) at interfaces.c:340
#6 0x00000000004022c9 in get_interfaces_info (iface=0x7f36b4004560) at interfaces.c:87
#7 0x0000000000402d9d in get_all_system_info () at kernel.c:109
#8 0x00007f36c07cce9a in start_thread (arg=0x7f36bb729700) at pthread_create.c:308
#9 0x00007f36c04f93fd in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:112
#10 0x0000000000000000 in ?? ()
(gdb)
Run Code Online (Sandbox Code Playgroud)
有人知道在这种情况下会发生什么事吗?我做错了什么,可以看出是什么?
非常感谢.
char arquivo[10]; // <-- here
sprintf(arquivo, "/sys/class/net/%s/address", iface->interface_name);
Run Code Online (Sandbox Code Playgroud)
arquivo对于那个字符串来说太小了.
您还应该检查open()的返回值:
fd = open(arquivo, O_RDONLY, 0);
if(fd < 0) {
perror("open");
// do something
}
Run Code Online (Sandbox Code Playgroud)
这也错了:
read(fd, buf, sizeof (buf));
buf[strlen(buf) - 1] = '\0';
^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
read()不会null终止任何东西.你不能在buf上调用strlen().代替:
int n = read(fd, buf, sizeof (buf));
if(n < 0) {
perror("read");
// do something
}
buf[n] = '\0';
Run Code Online (Sandbox Code Playgroud)