How to print a null-terminated string with newlines without showing backslash escapes in gdb?
Asked Answered
A

2

70

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?

Adjudge answered 7/10, 2009 at 10:23 Comment(4)
if nought else works, you can replace the '\n' with '\x0a' - this will the linefeed char directly.Castoff
@slashmais: This will still show up as \n in gdb outputExacting
Actually, I came here for a way to PRINT the \n >.> .. I was able to do this: print (char*)[nsstring cString]Downey
For those who don't care about the \n, use: x/s xPlotter
E
124

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)
Exacting answered 7/10, 2009 at 10:30 Comment(3)
I can't use stdout or stderr because these channels are attached to other program.Guidry
Note that it's important to terminate the printf command with a /n if your char* doesn't already end with one.Beatrix
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.Whittington
B
37

Use the string specifier:

print /s x
Battery answered 8/1, 2014 at 0:6 Comment(5)
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.Whittington
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.Preacher
This will not work when the string is larger than some length. It gets truncated when printing. printf method does print the full string.Lighterman
when your string is in a buffer then "p/s (char *)buff"Shote
In response to @Lighterman see https://mcmap.net/q/80260/-how-do-i-print-the-full-value-of-a-long-string-in-gdb and try set print elements 0Cushitic

© 2022 - 2024 — McMap. All rights reserved.