c - When does printf("%s", char*) stop printing? -
in class writing our own copy of c's malloc() function. test code (which can allocate space fine) using:
char* ptr = my_malloc(6*sizeof(char)); memcpy(ptr, "hello\n", 6*sizeof(char)); printf("%s", ptr); the output typically this:
hello unprintable character some debugging figured code wasn't causing per se, ptr's memory follows:
[24 bytes of meta info][number of requested bytes][padding]
so figured printf reaching padding, garbage. ran test of: printf("%s", "test\nd"); , got:
test d which makes me wonder, when printf("%s", char*) stop printing chars?
it stops printing when reaches null character (\0), because %s expects string null terminated (i.e., expects argument c string).
the string literal "test\nd" null terminated (all string literals null terminated). character array ptr not, however, because copy 6 characters buffer (hello\n), , not copy seventh character--the null terminator.
Comments
Post a Comment