Skip to content

Instantly share code, notes, and snippets.

@chenhengqi
Last active December 23, 2020 11:43
Show Gist options
  • Save chenhengqi/370efb5205b39f86ca54430d93f7512b to your computer and use it in GitHub Desktop.
Save chenhengqi/370efb5205b39f86ca54430d93f7512b to your computer and use it in GitHub Desktop.
Dive into C++

Code Snippet

#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <thread>


auto compute_e(int r) {
    auto e = 2.0;
    auto factorial = 1.0;

    for (auto i = 2; i < r; i++) {
        factorial *= i;
        e += 1 / factorial;
    }
    return e;
}

int main() {
    while (true) {
        auto r = rand() % 10000;
        auto e = compute_e(r);
        printf("%4d %.15lf\n", r, e);
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    return 0;
}

Symbols

$ g++ -Wall -std=c++17 -g -o app main.cpp
$ objdump --sym app | grep compute_e
0000000000401190 g     F .text  000000000000006f              _Z9compute_ei
$ c++filt _Z9compute_ei
compute_e(int)

Assembly

$ g++ -S -fverbose-asm main.cpp
$ objdump -d app | grep -A 10 _Z9compute_ei

Debug

$ gdb ./app
(gdb) info files
(gdb) break main.cpp:8
(gdb) break compute_e
(gdb) break _Z9compute_ei
(gdb) backtrace
(gdb) frame ${level}
(gdb) info registers
(gdb) display /4i _Z9compute_ei

Tracing

$ strace -p $PID
$ gstack -p $PID
$ pstack -p $PID
@chenhengqi
Copy link
Author

chenhengqi commented Dec 23, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment