[英]Debug Python/C++ program with bad_alloc
我有一個與 PyBind11 C++ 庫接口的 Python 程序。
在圖書館的某個地方,有些東西正在拋出std::bad_alloc
。 Python 捕捉到這一點並輕松引發異常:
MemoryError: std::bad_alloc
在 GDB 中運行它:
gdb --ex run --args python3 ./my_program
在分配錯誤時不會導致中斷。
如果我可以讓 Python 對錯誤分配進行段錯誤或告訴 GDB 在 Python 之前捕獲異常,我將能夠調試它。 不幸的是,我也不知道該怎么做。
調試它需要幾個步驟。 首先,我們需要調試符號。 PyBind11 剝離了這些,因此我們必須將它們取回。
我的 CMake 文件如下所示:
cmake_minimum_required(VERSION 3.10)
find_package(pybind11 REQUIRED)
pybind11_add_module(my_python_module my_python_module.cpp)
target_compile_features(my_python_module PUBLIC cxx_std_17)
要找回符號,我需要它看起來像這樣:
cmake_minimum_required(VERSION 3.10)
find_package(pybind11 REQUIRED)
pybind11_add_module(my_python_module my_python_module.cpp)
target_compile_features(my_python_module PUBLIC cxx_std_17)
target_link_libraries(my_python_module PRIVATE pybind11::module)
add_library(restore_default_visibility INTERFACE)
target_compile_options(restore_default_visibility INTERFACE -fvisibility=default)
target_link_libraries(my_python_module PRIVATE restore_default_visibility)
我還需要一個調試版本:
cmake -DCMAKE_BUILD_TYPE=Debug ..
現在,我可以啟動我的 Python 程序:
gdb --args python3 ./my_program
一個 GDB 啟動,我為std::bad_alloc
設置了一個斷點:
catch throw std::bad_alloc
現在我可以通過輸入c
來運行我的程序。
后來,當它崩潰時,我可以使用bt
命令獲取回溯, up
和down
導航堆棧, print
顯示變量的內容,以及Ctrl+X+A
來查看源代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.