Not null-terminating a C-style string

后端 未结 6 2127
萌比男神i
萌比男神i 2021-01-24 12:08

Given a string , say ,

char *str = \"Hello,StackOverflow!\"
char newStr[30];
int l = strlen(str);
for(int i =0 ; i

        
6条回答
  •  误落风尘
    2021-01-24 12:27

    I would suspect that most of the time it would keep printing past the "!" and keep going in memory until it hits a NULL. Which could result in a crash, but doesn't have to.

    This is why it's best to either:

    memset(newStr, 0, 30);
    

    or

    // This works because string literals guarantee a '\0' is present
    // but the strlen returns everything up until the '\0'
    int l = strlen(str) + 1;
    

    this works too, but I don't feel it's as clear as adding one to strlen:

    for(i =0 ; i<=l ; i ++ )
    

    As the defination of strlen implies you need to.

提交回复
热议问题