开发者

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

开发者 https://www.devze.com 2023-01-26 15:36 出处:网络
My program is as follows; #include <stdio.h> #include <string.h> int main() { char string[] = \"Gentlemen start your engines!\";

My program is as follows;

#include <stdio.h>
#include <string.h>

int main()
{
        char string[] = "Gentlemen start your engines!";
        printf("That string is %s characters long.\r\n", strlen(string));
        return 0;
}

I'm compiling under gcc, and although it doesn't give me any errors the 开发者_运维问答program crashes every time I run it. The code seems to be fine from examples I've seen. It'd be great to know if I'm doing anything wrong.

Thanks.


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));


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消