printf("%s", char*) 何时停止打印? [英] When does printf("%s", char*) stop printing?

查看:115
本文介绍了printf("%s", char*) 何时停止打印?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的课堂上,我们正在编写自己的 C 语言 malloc() 函数副本.为了测试我的代码(目前可以很好地分配空间),我使用了:

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

输出通常是这样的:

Hello
Unprintable character

一些调试认为我的代码本身并没有导致这种情况,因为 ptr 的内存如下:

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

[24 字节元信息][请求的字节数][填充]

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

所以我认为 printf 进入了填充,这只是垃圾.所以我进行了以下测试:printf("%s", "test\nd"); 得到:

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

test
d

这让我想知道,什么时候 printf("%s", char*) 停止打印字符?

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

推荐答案

它在遇到空字符 (\0) 时停止打印,因为 %s 需要以空字符结尾的字符串(即,它期望参数是一个 C 字符串).

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).

字符串文字 "test\nd" 以 null 结尾(所有字符串文字都以 null 结尾).但是,您的字符数组 ptr 不是,因为您只将六个字符复制到缓冲区中 (Hello\n),并且您没有复制第七个字符——空值终结者.

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.

这篇关于printf("%s", char*) 何时停止打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆