为什么strcpy的"工作"写malloc分配内存时,是不是足够大? [英] Why does strcpy "work" when writing to malloc'ed memory that is not large enough?

查看:121
本文介绍了为什么strcpy的"工作"写malloc分配内存时,是不是足够大?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/7139867/why-does-this-intentionally-incorrect-use-of-strcpy-not-fail-horribly\">Why这是否故意不正确使用的strcpy不可怕的失败?

下面见下文code:

char* stuff = (char*)malloc(2);
 strcpy(stuff,"abc");
 cout<<"The size of stuff is : "<<strlen(stuff);

尽管我分配2个字节的东西,为什么仍然strcpy的工作和strlen的输出是3.不宜这个扔东西像索引越界?

Even though I assigned 2 bytes to stuff, why does strcpy still work and the output of strlen is 3. Shouldn't this throw something like index out of bounds?

推荐答案

C和C ++不做自动边界检查,如Java和C#做。这code将覆盖在内存过去字符串末尾的东西,破坏无论在那里。这可能会导致奇怪的行为或崩溃后,所以这是很好的谨慎对待这样的事情。

C and C++ don't do automatic bounds checking like Java and C# do. This code will overwrite stuff in memory past the end of the string, corrupting whatever was there. That can lead to strange behavior or crashes later, so it's good to be cautious about such things.

访问过去的数组的末尾是由C和C ++标准被视为未定义行为。这意味着该标准没有规定当程序确实必须发生什么,所以触发UB程序是永不永不土地上的任何可能发生的事情。它可能会继续,没有明显问题的工作。它可能会立即崩溃。做别的事情,不应该是一个问题,当它以后可能会崩溃。它可能表现不好,但不会崩溃。或者,伶盗龙属可能出现吃你。任何事情都有可能发生。

Accessing past the end of an array is deemed "undefined behavior" by the C and C++ standards. That means the standard doesn't specify what must happen when a program does that, so a program that triggers UB is in never-never-land where anything might happen. It might continue to work with no apparent problems. It might crash immediately. It might crash later when doing something else that shouldn't have been a problem. It might misbehave but not crash. Or velociraptors might come and eat you. Anything can happen.

写作过去的数组的末尾被称为缓冲区溢出,顺便说一下,和它的安全漏洞的常见原因。如果ABC字符串实际上是用户输入的,熟练的攻击者可以把字节到它的最终覆盖类似函数的返回指针,它可以被用来制造比它应该运行不同的code程序,做不同的东西比它应该。

Writing past the end of an array is called a buffer overflow, by the way, and it's a common cause of security flaws. If that "abc" string were actually user input, a skilled attacker could put bytes into it that end up overwriting something like the function's return pointer, which can be used to make the program run different code than it should, and do different things than it should.

这篇关于为什么strcpy的&QUOT;工作&QUOT;写malloc分配内存时,是不是足够大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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