CWE -- Out-of-bounds Write 例子

CWE-787,也称为Out-of-bounds Write,是编程中的一种常见错误,可能导致敏感信息破坏、程序崩溃或代码执行。文章通过两个示例解释了这种错误的发生情况,强调了在使用指针或数组时未检查边界可能导致的问题。特别是在示例2中,由于未检查returnChunkSize()的返回值,memcpy可能会复制远超预期大小的内存块,从而引发严重后果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文地址:

https://cwe.mitre.org/data/definitions/787.html


1. 什么是 out-of-bound write  

Description Summary

The software writes data past the end, or before the beginning, of the intended buffer.

Extended Description

This typically occurs when the pointer or its index is incremented or decremented to a position beyond the bounds of the buffer or when pointer arithmetic results in a position outside of the valid memory location to name a few. This may result in corruption of sensitive information, a crash, or code execution among other things.


Example 1

The following code attempts to save four different identification numbers into an array.

(Bad Code)
Example Language: 
int id_sequence[3];

/* Populate the id array. */

id_sequence[0] = 123;
id_sequence[1] = 234;
id_sequence[2] = 345;
id_sequence[3] = 456;

Example 2

In the following example, it is possible to request that memcpy move a much larger segment of memory than assumed:

(Bad Code)
Example Language: 
int returnChunkSize(void *) {
/* if chunk info is valid, return the size of usable memory,
* else, return -1 to indicate an error
*/
...
}
int main() {
...
memcpy(destBuf, srcBuf, (returnChunkSize(destBuf)-1));
...
}

If returnChunkSize() happens to encounter an error it will return -1. Notice that the return value is not checked before the memcpy operation (CWE-252), so -1 can be passed as the size argument to memcpy() (CWE-805). Because memcpy() assumes that the value is unsigned, it will be interpreted as MAXINT-1 (CWE-195), and therefore will copy far more memory than is likely available to the destination buffer (CWE-787CWE-788).

重点: returnChunkSize() 需要被check 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值