没有结尾符的字符串为何会“烫烫烫烫烫”

添加时间:2018-02-28 08:21:29

相信经常用VC的朋友对屏幕输出的一大堆“烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫”不会陌生,但是也许会很奇怪,为什么会出现“烫”字呢?莫非改程序导致系统运行缓慢,发热过高???非也!下面让我解释一下吧,有错误的地方请指正:

在上一篇文章中,我们逆向了Debug模式下的一个C程序,发现栈区开辟的存储空间都是使用0CCCCCCCCh来填充4字节单位的,也就是说,栈区开辟的存取局部变量的空间的每一个字节都被0xCC填充了。(为什么用0xCC,这个是int 3h的机器码,下断点用的)两个0xCC合起来输出时恰好对应中文“烫”字。
这也就不奇怪程序输出那么多“烫”了。


实例一:
// 如果不建立工程,请大家自己修改一下头文件
#include "stdafx.h"
#include <string.h>
 
int _tmain(int argc, _TCHAR* argv[])
{
    char s[256] = {0};            // 定义一个数组
    memset(s, 0xCC, sizeof(s));    // 用0xCC填充
    printf("%s\n", s);            // 输出
    return 1;
}

// 如果不建立工程,请大家自己修改一下头文件
#include "stdafx.h"
#include <string.h>
 
int _tmain(int argc, _TCHAR* argv[])
{
    char s[256] = {0};            // 定义一个数组
    memset(s, 0xCC, sizeof(s));    // 用0xCC填充
    printf("%s\n", s);            // 输出
    return 1;
}

大家可以自己查看运行结果,程序输出很多烫字。

实例二:
// 如果不建立工程,请大家自己修改一下头文件
#include "stdafx.h"
#include <string.h>
 
int _tmain(int argc, _TCHAR* argv[])
{
    char s[256];                // 系统默认用0xCC填充
    printf("%s\n", s);            // 输出
    return 1;
}
    
// 如果不建立工程,请大家自己修改一下头文件
#include "stdafx.h"
#include <string.h>
 
int _tmain(int argc, _TCHAR* argv[])
{
    char s[256];                // 系统默认用0xCC填充
    printf("%s\n", s);            // 输出
    return 1;
}

程序输出还是”很烫“。

实例三:把字符数组定义为全局变量
// 如果不建立工程,请大家自己修改一下头文件
#include "stdafx.h"
#include <string.h>
 
char s[256];        // 全局变量
 
int _tmain(int argc, _TCHAR* argv[])
{
    printf("%s\n", s);            // 输出
    return 1;
}
    
// 如果不建立工程,请大家自己修改一下头文件
#include "stdafx.h"
#include <string.h>
 
char s[256];        // 全局变量
 
int _tmain(int argc, _TCHAR* argv[])
{
    printf("%s\n", s);            // 输出
    return 1;
}

这次系统输出了空,没有烫了!为什么,请读者自己思考。

其实,全局变量分配在”全局/静态存储区“中,局部变量分配在栈中,我们可以定义一个很大的数组,如果是局部的,会导致程序栈溢出,因为栈的空间大小是有限制的;而全局的则不会。

另外需要注意,这些”烫烫烫烫烫烫烫“现象只会在Debug模式中出现,在Release模式中不会出现。

如果你对”烫烫烫烫烫烫烫“表示很熟悉,那么”屯屯屯屯屯屯屯屯屯屯屯屯屯屯屯屯“你见过吗?应该吧。我本人以前经常遇到”烫“,但很少遇到后者。

实例四:动态分配内存空间
// 如果不建立工程,请大家自己修改一下头文件
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
 
int main(int argc, char* argv[])
{
    char *s = (char *)malloc(sizeof(char) * 256);
    puts(s);
    free(s);
    return 0;
}
    
// 如果不建立工程,请大家自己修改一下头文件
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
 
int main(int argc, char* argv[])
{
    char *s = (char *)malloc(sizeof(char) * 256);
    puts(s);
    free(s);
    return 0;
}

运行程序,顿时满屏的”屯“字出现在眼前。

因为,动态分配的空间开辟与堆,VC的Debug用0xCD填充堆的空间,两个0xCD和在一起就是屯了。
试着去反汇编跟踪了一下,实在是跳来跳去麻烦,放弃了。
本文涉及到的中文编码与变量存放位置并没有详细讲解,读者请自己查阅相关资料。

标签: C++  易学C++  
专题: 易学C++  
Tag: C++  易学C++  

评论

comment

用户名 Name
验证码
评论 Comment
返回前一页
Powered by CmsEasy

分享到: