When does printf(“%s”, char*) stop printing?

前端 未结 4 739
天命终不由人
天命终不由人 2021-01-11 10:19

In my class we are writing our own copy of C\'s malloc() function. To test my code (which can currently allocate space fine) I was using:

char* ptr = my_mal         


        
4条回答
  •  情歌与酒
    2021-01-11 10:41

    C strings are null terminated (there's a \0 character at the end), that's how C knows when to stop printing or dealing with the buffer as a string . It is your responsibility to never put a string in a longer space than what you have allocated.

    Note that Hello\n is not a six character string, it is actually a seven character string. You use five for the Hello, one for the newline, and one for the null terminator.

    Trying to fit 7 characters into a six character buffer is considered a bug, I am not sure if it is responsible for the problems you are currently having, but it seems like the copying of 6 characters would not copy the null terminator. So I would actually expect your print to go beyond the Hello and into some actual junk.

提交回复
热议问题