When debugging with GDB I would like to set a convenience variable to a newly constructed value.
I am programming using the Qt framework, so i would like to create a QString, but this is irrelevant to the question, since I would like to know how to do this with any class.
I tried
(gdb) set $str = 'QString::QString("abc")'
No symbol "QString::QString("abc")" in current context.
(gdb) set $str = QString::QString("abc")
Cannot resolve method QString::QString to any overloaded instance
(gdb) set $str = QString("abc")
A syntax error in expression, near `("abc")'.
then I tried using set overload-resolution off
, resulting in the following:
set $str = QString::QString("abc")
non-unique member `QString' requires type instantiation
set $str = 'QString::QString(const char*)'("abc")
Too few arguments in function call.
So I assumed a this pointer is needed:
(gdb) set $str = 'QString::QString(const char*)'(malloc(sizeof(QString)), "abc")
(gdb) p $str
$8 = void
Okay, constructors return void, that means I have to save the return value of malloc somewhere:
(gdb) set $pointer = malloc(sizeof(QString))
(gdb) p $pointer
$9 = 6304560
(gdb) p/x $pointer
$10 = 0x603330
(gdb) set $str = 'QString::QString(const char*)'($pointer, "abc")
(gdb) p $str
$11 = void
(gdb) p $pointer
$12 = 6304560
(gdb) p *((QString*)$pointer)
$13 = "abc"
Okay, now this works as expected, however I want to use this code in gdb.parse_and_eval() for a python pretty printer. Now this will call malloc lots of times, creating a memory leak. So just call free()? Now something unexpected happens:
(gdb) call free($pointer)
$14 = 0
(gdb) p *((QString*)$pointer)
$15 = "abc"
The pointer still seems valid, which may of course be perfectly fine, since the memory has not been reused. However I am unsure whether this is okay because after allocating a few more memory blocks which fit exactly one QString the pointer value has still not been reused by malloc.
Am I creating a big memory-leak if I use this in a pretty-printer, which may well be called lots of times during a debug session? Is there any easier solution of creating the desired result (i.e. using the Python API)?
Also unrelated to this, why is free(3) giving me a return value of 0 while it is actually void?