【原创】GDB调试时如何格式化(pretty print)打印结构体内容?

blogdaren 2021-01-03 抢沙发 38人次

问题背景:

GDB调试C程序时,经常需要打印结构体的内容,默认情况下输出很不直观,看起来很费劲,比如:

(gdb) p *ht
$6 = {gc = {refcount = 1, u = {v = {type = 7 '\a', flags = 0 '\000', gc_info = 0}, type_info = 7}}, u = {v = {flags = 18 '\022', nApplyCount = 0 '\000', 
      nIteratorsCount = 0 '\000', reserve = 0 '\000'}, flags = 18}, nTableMask = 4294967294, arData = 0x845cd5c, nNumUsed = 0, nNumOfElements = 0, nTableSize = 8, 
  nInternalPointer = 4294967295, nNextFreeElement = 0, pDestructor = 0x82581ff <_zval_ptr_dtor_wrapper>}

解决方案:

GDB对此早有考虑,所以给我们提供了很多可配置的选项,对于结构体,只需打开如下配置即可:(gdb) set print pretty on

效果展示:

(gdb) 
$9 = {
  gc = {
    refcount = 1, 
    u = {
      v = {
        type = 7 '\a', 
        flags = 0 '\000', 
        gc_info = 0
      }, 
      type_info = 7
    }
  }, 
  u = {
    v = {
      flags = 18 '\022', 
      nApplyCount = 0 '\000', 
      nIteratorsCount = 0 '\000', 
      reserve = 0 '\000'
    }, 
    flags = 18
  }, 
  nTableMask = 4294967294, 
  arData = 0x845cd5c, 
  nNumUsed = 0, 
  nNumOfElements = 0, 
  nTableSize = 8, 
  nInternalPointer = 4294967295, 
  nNextFreeElement = 0, 
  pDestructor = 0x82581ff <_zval_ptr_dtor_wrapper>
}

扩展知识:

除了结构体外,GDB还针对联合体、数组等实体提供了类似的配置指令,格式均为:

//查看某个实体的当前配置
show print 实体

//打开或关闭某个实体配置
set  print 实体 [on|off]

//比如查看数组以及打开或关闭数组开关
show print array
set  print array on
set  print array off

版权声明:除非注明,本文由( blogdaren )原创,转载请保留文章出处。

本文链接:【原创】GDB调试时如何格式化(pretty print)打印结构体内容?

发表评论:

您的昵称:
电子邮件:
个人主页:

Free Web Hosting