最常用的调试C++程序的方法是使用IDE,比如说vs,clion。打断点,debug模式跑。
稍微先进一点的是使用gdb进行调试。
gdb调试使用到的技术就比较多了,以后详细介绍。
今天看到一个神奇的命令addr2line
,这个命令可以在程序 core dump的时候告诉你程序在哪一行出错。
示例代码如下:
int main(void) {
char *str;
/* Stored in read only part of data segment */
str = "core dump";
/* Problem: trying to modify read only memory */
*(str + 1) = 'n';
return 0;
}
编译运行:
-> # g++ -ggdb -o test test.cpp
-> # dmesg -C
-> # ./test
[1] 27108 segmentation fault (core dumped) ./test
-> # dmesg
[7191229.141592] test[27108]: segfault at 400595 ip 00000000004004ff sp 00007fffd8a65f50 error 7 in test[400000+1000]
会报错:segmentation fault (core dumped)
然后使用addr2line
:
-> # addr2line -afiCe test 00000000004004ff
0x00000000004004ff
main
/root/test.cpp:19
告诉你出错的代码在main函数,代码第19行。