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

前端 未结 4 695
天命终不由人
天命终不由人 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:33

    James is correct about printf stopping when it gets to the null character, and Uri is correct that you need to allocate a 7-character buffer to hold "hello\n".

    Some of the confusion with terminators would be mitigated if you used the usual C idiom for copying a string: strcpy(ptr, "Hello\n"), rather than memcpy.

    Also, by definition, sizeof(char) == 1 in C, so 6*sizeof(char) is redundant

    0 讨论(0)
  • 2021-01-11 10:39

    It stops printing when it reaches a null character (\0), because %s expects the string to be null terminated (i.e., it expects the argument to be a C string).

    The string literal "test\nd" is null terminated (all string literals are null terminated). Your character array ptr is not, however, because you only copy six characters into the buffer (Hello\n), and you do not copy the seventh character--the null terminator.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-11 10:42

    when it reaches a zero. you need 7 chars.

    0 讨论(0)
提交回复
热议问题