Why does using the wrong format specifier in C crash my program on Windows 7? Why does using the wrong format specifier in C crash my program on Windows 7? c c

Why does using the wrong format specifier in C crash my program on Windows 7?


Using incorrect format specifier in printf() invokes Undefined Behaviour. Correct format specifier should be %zu (not %d) because the return type of strlen() is size_t

Note: Length modifier z in %zu represents an integer of length same as size_t


You have wrong format specifier. %s is used for strings but you are passing size_t (strlen(string)). Using incorrect format specifier in printf() invokes undefined behaviour. Use %zu instead because the return type of strlen() is size_t.

So change

 printf("That string is %s characters long.\r\n", strlen(string));

to:

 printf("That string is %zu characters long.\r\n", strlen(string));

Since you are using gcc have a look here for more info what can be passed to printf


 printf("That string is %d characters long.\r\n", strlen(string));

instead:

 printf("That string is %s characters long.\r\n", strlen(string));