66

I have a variable

char* x = "asd\nqwe\n ... "

and I want to print it with newlines printed as newlines not backslash n. Is it possible?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Łukasz Lew
  • 48,526
  • 41
  • 139
  • 208

2 Answers2

116

Update: Why not just use the gdb printf command?

(gdb) printf "%s", x
asd
qwe
...
(gdb)

Old answer: From within the debugger you can execute commands. Just call printf

(gdb) call printf("%s", x)
asd
qwe
...
(gdb)
Anton Samsonov
  • 1,380
  • 17
  • 34
ezpz
  • 11,767
  • 6
  • 38
  • 39
  • I can't use stdout or stderr because these channels are attached to other program. – Łukasz Lew Oct 07 '09 at 10:37
  • 9
    Note that it's important to terminate the printf command with a /n if your char* doesn't already end with one. – Ben Flynn Sep 12 '12 at 23:24
  • 1
    Worth to note that `printf()` function call may succeed and return the number of characters in the string, but not actually output those characters on the screen; the same holds true for `puts()` function call and perhaps others of that kind. In contrast, the built-in `printf` command works as expected. – Anton Samsonov Jul 21 '15 at 10:46
36

Use the string specifier:

print /s x
Paul Richter
  • 10,908
  • 10
  • 52
  • 85
netskink
  • 4,033
  • 2
  • 34
  • 46
  • 4
    This is definitely better than calling the debugged program's functions like `printf`, but may only work on relatively new versions of GDB: mine yields “Format letter "s" is meaningless in "print" command”, for example. – Anton Samsonov Jul 21 '15 at 10:33
  • 5
    This don't work when `x` is a variable other than address, in that case, need use `x` command, e.g `x/s x`, or need a type convert, e.g `p (char *) &x`. – Eric May 23 '16 at 07:36
  • 3
    This will not work when the string is larger than some length. It gets truncated when printing. printf method does print the full string. – sadashiv30 Aug 09 '17 at 18:16
  • 1
    when your string is in a buffer then "p/s (char *)buff" – RichieHH Nov 20 '20 at 05:02