C creates extra bytes in buffer

后端 未结 2 412
渐次进展
渐次进展 2021-01-26 19:48

I\'ve been messing around with C today and don\'t understand the difference in outputs when I comment out the third buffer in this code:

 #include 

        
2条回答
  •  清歌不尽
    2021-01-26 20:39

    Try this:

    memset(letters, 0x00, 10);
    memset(letters, 0x41, 9);   /* <--- see the array size minus one there */
    

    that will make the printf(3) to work properly, but printing a list of nine As only. As explained in other responses, this has to do with the nightmare for C programmers to null terminate strings built by hand. For that reason is more common to use the functions.

    In another place, using printf()'s first parameter without a string literal is discouraged, as in the case your string had a % character, that would be interpreted as a format descriptor, and you would had run into more Undefined behaviour, again.

提交回复
热议问题