Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
859 views
in Technique[技术] by (71.8m points)

c - When does printf("%s", char*) stop printing?

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_malloc(6*sizeof(char));
memcpy(ptr, "Hello
", 6*sizeof(char));
printf("%s", ptr);

The output would typically be this:

Hello
Unprintable character

Some debugging figured that my code wasn't causing this per se, as ptr's memory is as follows:

[24 bytes of meta info][Number of requested bytes][Padding]

So I figured that printf was reaching into the padding, which is just garbage. So I ran a test of: printf("%s", "test d"); and got:

test
d

Which makes me wonder, when DOES printf("%s", char*) stop printing chars?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

The string literal "test d" 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 ), and you do not copy the seventh character--the null terminator.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...