Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string manipulation with %s format

Tags:

c

May you explain the following output:

main()
{
   char f[] = "qwertyuiopasd";
   printf("%s\n", f + f[6] - f[8]);
   printf("%s", f + f[4] - f[8]);
}

output:

uiopasd
yuiopasd

For example regarding the first printf:

f[8] should represent the char 'o'

f[6] should represent the char 'u'

%s format prints the string (printf("%s", f) is giving the whole "qwertyuiopasd")

So how does it come together, what is the byte manipulation here?

like image 632
temp Avatar asked Dec 31 '22 22:12

temp


1 Answers

There are multiple problems in the code posted:

  • the missing return type for main is an obsolete syntax. you should use int main().
  • the prototype for printf is not in scope when the calls are compiled. This has undefined behavior. You should include <stdio.h>.
  • the expression f + f[6] - f[8] has undefined behavior: addition is left associative, so f + f[6] - f[8] is evaluated as (f + f[6]) - f[8]. f[6], which is the letter u is unlikely to have a value less than 14 (in ASCII, its value is 117) so f + f[6] points well beyond the end of the string, thus is an invalid pointer and computing f + f[6] - f[8] has undefined behavior, in spite of the fact that 'u' - 'o' has the value 6 for the ASCII character set. The expression should be changed to f + (f[6] - f[8]).

Assuming ASCII, the letters o, u and t have values 111, 117 and 116. f + (f[6] - f[8]) is f + ('u' - 'o') which is f + (117 - 111) or f + 6.

f + 6 is the address of f[6], hence a pointer to the 7th character of the string "qwertyuiopasd". Printing this string produces uiopasd.

like image 192
chqrlie Avatar answered Jan 08 '23 17:01

chqrlie