My program is as follows;
#include
#include
int main()
{
char string[] = \"Gentlemen start your engines!\";
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
You have a problem here
printf("That string is %s characters long.\r\n", strlen(string));
put
printf("That string is %d characters long.\r\n", strlen(string));
%d because you want to printthe length of str (strlen returns number)
Program crashes because formatting routine tries to access a string at address 0x0000001D
which is the result of strlen()
where is nothing like a string and likely there's no acessible memory at all.
printf("That string is %d characters long.\r\n", strlen(string));
instead:
printf("That string is %s characters long.\r\n", strlen(string));