Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with this format string?

I have a string like this:

<string name="q_title" formatted="false">Item %d of %d</string>

I'm using it in String.format like this:

String log = String.format(getString(R.string.q_title), 100, 500);

So far I've observed no problems with the output.

However, code inspection in Android Studio gives me:

Format string 'q_title' is not a valid format string so it should not be passed to String.format

Why?

like image 935
Alexander Kulyakhtin Avatar asked Jul 06 '13 12:07

Alexander Kulyakhtin


People also ask

Which of the format string is not valid?

Format string XXX is not a valid format string so it should not be passed to String.

What causes format string vulnerability?

Format String attacks alter the flow of an application. They use string formatting library features to access other memory space. Vulnerabilities occurred when the user-supplied data is deployed directly as formatting string input for certain C/C++ functions (e.g., fprintf, printf, sprintf, setproctitle, syslog, ...).

What is format string in C++?

The sprintf() function in C++ is used to write a formatted string to character string buffer. It is defined in the cstdio header file.


2 Answers

Your string should be

<string name="q_title" formatted="false">Item %1$d of %2$d</string>

And code

String log = getString(R.string.q_title, 100, 500);

When you have multiple arguments you need to mark them with 1$, 2$... n$. In arabian langs order is reversed, so they need to know how to change it correctly.

getString(id, args...) perform format in itself.

like image 83
Roger Alien Avatar answered Oct 14 '22 23:10

Roger Alien


For percent, the following worked for me.

<string name="score_percent">%s%%</string>


getString(R.string.score_percent,"20")

If you are dealing with integers replace s by d

<string name="score_percent">%d%%</string>
like image 40
Lazy Ninja Avatar answered Oct 14 '22 21:10

Lazy Ninja