Why doesn't the compiler detect out-of-bounds in string constant initialization?

后端 未结 6 1843
误落风尘
误落风尘 2021-01-18 00:13

I read this question and its answer in a book. But I didn\'t understand the book\'s justification.

Will the following code compile?

6条回答
  •  不知归路
    2021-01-18 00:53

    Your book must be pretty old, because gcc puts out a warning even without -Wall turned on:

    $ gcc c.c
    c.c: In function `main':
    c.c:6: warning: initializer-string for array of chars is too long
    

    If we slightly update the program:

    #include 
    
    int main(int argc, char **argv)
    {
    
            char str[5] = "1234567890";
            printf("%s\n", str);
            return 0;
    }
    

    We can see that gcc seems to truncate the string to the length you've specified; I'm assuming that there happens to be a '\0' where str[6] would be, because otherwise we should see garbage after the 5; but maybe gcc implicitly makes str an array of length 6 and automatically sticks the '\0' in there - I'm not sure.

    $ gcc c.c && ./a.exe
    c.c: In function `main':
    c.c:6: warning: initializer-string for array of chars is too long
    12345
    

提交回复
热议问题