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

前端 未结 5 1559
后悔当初
后悔当初 2020-12-11 14:56

My program is as follows;

#include 
#include 

int main()
{
        char string[] = \"Gentlemen start your engines!\";
                


        
相关标签:
5条回答
  • 2020-12-11 15:34

    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

    0 讨论(0)
  • 2020-12-11 15:37

    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

    0 讨论(0)
  • 2020-12-11 15:41

    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)

    0 讨论(0)
  • 2020-12-11 15:41

    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 讨论(0)
  • 2020-12-11 15:44
     printf("That string is %d characters long.\r\n", strlen(string));
    

    instead:

     printf("That string is %s characters long.\r\n", strlen(string));
    
    0 讨论(0)
提交回复
热议问题