[英]Creating malloc() buffer overrun in C
I want to write a check unit test for malloc(3) using the "check library".我想使用“检查库”为 malloc(3) 编写检查单元测试。
This unit test is supposed to produce buffer overruns.这个单元测试应该会产生缓冲区溢出。
Could you please give me other simple examples for buffer overruns?你能给我其他关于缓冲区溢出的简单例子吗?
To overrun a buffer, you need to access a buffer outside its guaranteed size or before its beginning.要溢出缓冲区,您需要访问超出其保证大小或开始之前的缓冲区。 Allocation doesn't really access any visible buffers, so it's hard to see how any kind of allocation would be a buffer overrun unless there was a bug in the allocation routine itself or its structures were corrupted.
分配并不真正访问任何可见的缓冲区,因此很难看出任何类型的分配是如何造成缓冲区溢出的,除非分配例程本身存在错误或其结构已损坏。
Is allocating a double on an int variable (ie int *ptr = malloc(3)) a buffer overrun?
在 int 变量(即 int *ptr = malloc(3))上分配 double 是否会导致缓冲区溢出?
No, since no buffer is being accessed.不,因为没有访问缓冲区。
What about allocating a bigger number than the maximum value of an int?
分配比 int 最大值更大的数字怎么样?
No, since no buffer is being accessed.不,因为没有访问缓冲区。
To overrun a buffer, you must first have a buffer and then overrun it.要溢出缓冲区,您必须先拥有一个缓冲区,然后再溢出它。 For example:
例如:
int* j = malloc (2 * sizeof (int));
j[2] = 1;
Here I allocate a buffer with space for two integers and then overrun it by accessing the third integer (0 is the first, 1 is the second, so 2 is the third).在这里,我为两个整数分配了一个缓冲区,然后通过访问第三个整数(0 是第一个,1 是第二个,所以 2 是第三个)来溢出它。
Writing or reading past the end of a buffer allocated by malloc
produces undefined behavior , which means you can't depend on any particular behavior when it happens.写入或读取超过由
malloc
分配的缓冲区的末尾会产生未定义的行为,这意味着您不能依赖任何特定的行为发生时。 The program may appear to work, it may core dump, or it may output unexpected results.该程序可能看起来正常工作,可能会发生核心转储,或者可能会输出意外结果。
Because overrunning a malloc'ed buffer caused undefined behavior, creating test cases for it is pointless unless you're testing a particular implementation of malloc
.由于溢出
malloc
缓冲区会导致未定义的行为,因此除非您正在测试malloc
的特定实现,否则为其创建测试用例毫无意义。 Based on the wording of your question, that does not seem to be the case.根据您问题的措辞,情况似乎并非如此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.