先上程序
#include <stdio.h>
int divide(int a, int b) {
return a/b;
}
int main() {
fprintf(stdout, "input value\n");
int a = 3, b = 0;
int div = divide(a, b);
fprintf(stdout, "div value: %d\n", div);
return 0;
}
首先执行:
ubuntu:~/CPPWorkSpace/BasicCPP$ g++ -g main.cpp -o main
输出中包含一个文件 main, 如下图所示:
然后过滤一下:
ubuntu:~/CPPWorkSpace/BasicCPP$ dmesg | grep main
得到结果:
[ 0.246864] PCI: MMCONFIG for domain 0000 [bus 00-7f] at [mem 0xf0000000-0xf7ffffff] (base 0xf0000000)
[ 0.332945] PCI: MMCONFIG for domain 0000 [bus 00-7f] at [mem 0xf0000000-0xf7ffffff] (base 0xf0000000)
[ 0.357689] ACPI: PCI Root Bridge [PCI0] (domain 0000 [bus 00-7e])
[ 0.387227] iommu: Default domain type: Translated
[ 0.429714] NetLabel: domain hash size = 128
[ 1.182184] platform eisa.0: EISA: Cannot allocate resource for mainboard
[ 2.655487] intel_rapl_common: Found RAPL domain package
[ 2.655489] intel_rapl_common: Found RAPL domain core
[ 2.655489] intel_rapl_common: Found RAPL domain uncore
[ 2.655491] intel_rapl_common: Found RAPL domain dram
[ 7860.005797] traps: main[4727] trap divide error ip:55d8fcb1a6d8 sp:7ffd1c2168a0 error:0 in main[55d8fcb1a000+1000]
注意IP 字段符号,代表的是出错的位置地址
当前的执行环境是Ubuntu18.04 ,其实地址有偏移 ,所以要做作差
IP 地址减去后面的方框中地址,得到最终位置地址
55d8fcb1a6d8 — 55d8fcb1a000 = 6d8 (注意是十六进制)
所以写法为:0x6d8
ubuntu:~/CPPWorkSpace/BasicCPP$ addr2line -e main 0x6d8 -f -a -p -C
最终定位到如下的行数
0x00000000000006d8: divide(int, int) at /home/mi/CPPWorkSpace/BasicCPP/main.cpp:4
定位到函数和对应的行数