【问题标题】:Debug Python/C++ program with bad_alloc使用 bad_alloc 调试 Python/C++ 程序
【发布时间】:2020-04-24 20:39:18
【问题描述】:

我有一个与 PyBind11 C++ 库接口的 Python 程序。

在图书馆的某个地方,有东西​​正在抛出std::bad_alloc。 Python 捕捉到这一点并轻松引发异常:

MemoryError: std::bad_alloc

在 GDB 中运行它:

gdb --ex run --args python3 ./my_program

在分配错误时不会导致中断。

如果我可以让 Python 对错误分配进行段错误或告诉 GDB 在 Python 之前捕获异常,我就可以调试它。不幸的是,我也不知道该怎么做。

【问题讨论】:

    标签: python c++ gdb bad-alloc


    【解决方案1】:

    调试这需要几个步骤。首先,我们需要调试符号。 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 命令获取回溯,updown 导航堆栈,print 显示变量的内容,Ctrl+X+A 查看源代码。

    【讨论】:

      猜你喜欢
      • 2012-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-11
      • 2011-09-12
      相关资源
      最近更新 更多