DAY8-GDB调试及打桩
GDB打桩
1.类成员函数打桩
// example1.cpp
#include <iostream>class Calculator {
public:int add(int a, int b) {return a + b;}
};int main() {Calculator calc;std::cout << "Result: " << calc.add(2, 3) << std::endl;return 0;
}
(gdb) break Calculator::add
(gdb) run
(gdb) return 100 # 强制返回100
(gdb) continue
- 虚函数打桩
// example2.cpp
#include <iostream>class Base {
public:virtual void show() {std::cout << "Base show()" << std::endl;}
};class Derived : public Base {
public:void show() override {std::cout << "Derived show()" << std::endl;}
};int main() {Base* obj = new Derived();obj->show();delete obj;return 0;
}
(gdb) break Derived::show
(gdb) run
(gdb) jump Base::show # 跳转到基类实现
(gdb) continue
3.STL容器打桩
// example3.cpp
#include <iostream>
#include <vector>void printVector(const std::vector<int>& vec) {for (int num : vec) {std::cout << num << " ";}std::cout << std::endl;
}int main() {std::vector<int> numbers = {1, 2, 3};printVector(numbers);return 0;
}
(gdb) break main
(gdb) run
(gdb) p vec
# 假设输出为 {1, 2, 3} size=3# 尝试push_back
(gdb) call vec.push_back(4)
# 如果报错,尝试:# 方法1:类型转换
(gdb) call ((std::vector<int>*)&vec)->push_back(4)# 方法2:直接操作内部指针
(gdb) set $p = (int*)vec._M_impl._M_start
(gdb) set $p[3] = 4
(gdb) set vec._M_impl._M_finish = vec._M_impl._M_start + 4# 验证
(gdb) p vec
# 现在应该显示 {1, 2, 3, 4} size=4
- 模板函数打桩
// example4.cpp
#include <iostream>
#include <string>template<typename T>
T max(T a, T b) {return a > b ? a : b;
}int main() {std::cout << "Max: " << max(10, 20) << std::endl;std::cout << "Max: " << max(std::string("apple"), std::string("banana")) << std::endl;return 0;
}
(gdb) break 'int max<int>(int, int)'
(gdb) run
(gdb) return 1000 # 修改int版本的返回值
(gdb) continue
- 异常处理打桩
// example5.cpp
#include <iostream>
#include <stdexcept>void riskyFunction() {// 正常情况下不会抛出异常std::cout << "Normal execution" << std::endl;
}int main() {try {riskyFunction();std::cout << "No exception" << std::endl;} catch (const std::exception& e) {std::cout << "Exception: " << e.what() << std::endl;}return 0;
}
(gdb) break riskyFunction
(gdb) run
(gdb) call throw std::runtime_error("Forced by GDB")
(gdb) continue
GDB调试实战
学习链接:GDB调试C++的虚函数与多态