非空终止字符数组 [英] Not Null Terminated character array

查看:86
本文介绍了非空终止字符数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>

char s[3] = "Robert";
int main()
{
    printf("%s",s);
}

Output: Rob

如何正确打印?该字符串不是以null终止的. 我看到了集会.它使用.ascii存储不以null终止的"Rob". 我希望可以和Rob一起打印一些垃圾. 有人可以向我解释这种行为吗?

How does this get printed properly? The string is not null terminated. I saw the assembly. It used .ascii for storing "Rob" which is not null terminated. I expected some garbage along with Rob to be printed. Can someone explain me this behaviour?

推荐答案

您的"Rob"已存储在可执行文件的其他部分.可执行文件中的各节是对齐的,即,将具有数据的节用0填充,直到下一节为止.因此,printf从部分填充中获得了"0".为了说明:

Your "Rob" has been stored in an extra section of the executable. The sections in an executable are aligned, i.e. the section with the data is padded with 0 until the next section. So printf got "its" 0 from the section padding. To illustrate:

#include <stdio.h>

char dummy[] = "ocop";
char s[3] = "Robert";
char second[] = "in Hood";
int main( void )
{
    printf("%s",s);
    return 0;
}

输出(不进行优化的MinGW-GCC):罗宾汉
输出(具有优化的MinGW-GCC):Robocop

Output (MinGW-GCC w/o optimization): Robin Hood
Output (MinGW-GCC with optimization): Robocop

现在填充中没有0,而是下一个字符串的开头,也将输出该字符串.

Now there is no 0 from the padding but the begin of the next string which will be outputted as well.

这篇关于非空终止字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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