71

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?

4
  • if nought else works, you can replace the '\n' with '\x0a' - this will the linefeed char directly. Commented Oct 7, 2009 at 10:35
  • @slashmais: This will still show up as \n in gdb output Commented Oct 7, 2009 at 10:55
  • Actually, I came here for a way to PRINT the \n >.> .. I was able to do this: print (char*)[nsstring cString] Commented Mar 19, 2012 at 9:59
  • 2
    For those who don't care about the \n, use: x/s x Commented Jun 23, 2015 at 9:49

2 Answers 2

125

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)
Sign up to request clarification or add additional context in comments.

3 Comments

I can't use stdout or stderr because these channels are attached to other program.
Note that it's important to terminate the printf command with a /n if your char* doesn't already end with one.
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.
37

Use the string specifier:

print /s x

5 Comments

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.
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.
This will not work when the string is larger than some length. It gets truncated when printing. printf method does print the full string.
when your string is in a buffer then "p/s (char *)buff"
In response to @sadashiv30 see stackoverflow.com/a/233339/2796832 and try set print elements 0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.