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

后端 未结 6 1833
误落风尘
误落风尘 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:42

    What's happening is you're trying to initialize a character array with more characters than the array has room for. Here's how it breaks down:

    char str[5];
    

    Declares a character array with five characters.

    char str[5] = "fast enough";
    

    The second part '= "fast enough";' then attempts to initialize that array with the value "fast enough". This will not work, because "fast enough" is longer than the array is.

    It will, however, compile. C and C++ compilers can't generally perform bounds checking on arrays for you, and overrunning an array is one of the most common reasons for segmentation faults. [edit]As Mark Rushakoff pointed out, apparently the newer ones do throw warnings, for some cases.[/edit] This may segfault when you try to run it, more likely I think the array will simply be initialized to "fast ".

提交回复
热议问题