CHAR名称[1]为什么持有超过1个字符吗? [英] Why char name[1] can hold more than 1 character?

查看:170
本文介绍了CHAR名称[1]为什么持有超过1个字符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做的有关课题研究的一点点,当我遇到这种情况就来了。
假设下面的C code:

I was doing a little bit of research about a topic when I came across this situation. Assume the following C code:

#include <stdio.h>
int main() {
char name[1];
scanf("%s",name);
printf("Hi %s",name);
return 0;
}

我和 -fno-堆栈保护,并输入测试它长于1,如约翰&安培;出乎我的意料,它的工作原理!结果
难道不应该扔分割故障当输入的长度超过1?结果
最终,它与亚历山大爆发为输入(9),但它与任何小于9结果工作
为什么它比输入的名称数组长度较长的工作?结果
P.S:我使用Ubuntu(64位),gcc版本4.8.4(Ubuntu的4.8.4-2ubuntu1〜14.04)及克利翁的IDE。

I've compiled with -fno-stack-protector and tested it with input longer than 1, like John, & to my surprise, It works!
Shouldn't it throw a segmentation fault when the input is longer than 1?
Eventually it broke with Alexander as input (9) but it works with anything less than 9.
Why is it working with inputs longer than the name array length?
P.S : I'm using Ubuntu(64-bit), gcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04) & CLion as IDE.

推荐答案

这是不确定的行为。你的程序有一个缓冲区溢出,因为它分配一个字符,这足以存储一个空的空终止字符串。

This is undefined behavior. Your program has a buffer overrun, because it allocates exactly one character, which is sufficient for storing an empty null-terminated string.

然而,存在相邻尚未分配给你的程序的缓冲存储器中。 scanf函数放置您输入的内存,因为它不知道多长时间你的字符串缓冲区。这是一个很大的危险,无数的黑客攻击源,当pre-确定字节顺序放入您的字符串,在希望重写某些重要因素,并最终获得控制权。

However, there is memory adjacent to your buffer that has not been allocated to your program. scanf places your input into that memory, because it does not know how long is your string buffer. This is a big danger and a source of countless hacker attacks, when a pre-determined sequence of bytes is placed into your string, in hopes to override some vital elements, and eventually gain control.

这就是为什么使用%S 不指定大小是危险的。你需要一个合适的大小限制总是添加到%S ,否则你的程序在缓冲区溢出的危险。

That is why using %s without specifying the size is dangerous. You need to always add a proper size limit to %s, otherwise your program is in danger of buffer overrun.

char name[120];
scanf("%119s",name);

本程序是安全的,因为即使一个恶意用户类型超过120个字符, scanf函数会忽略过去的119个字符,如在规定的一切%119s 格式。

This program is safe, because even if a malicious user types more than 120 characters, scanf would ignore everything past 119-th character, as specified in %119s format.

这篇关于CHAR名称[1]为什么持有超过1个字符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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