此函数的目的是删除具有最高索引的元素,该元素基本上是数组的最后一个元素。我使用长度为5的数组运行此代码,并且它一直运行良好,直到它达到数组长度为0的点。然后突然之间,它因为ia&gt断言失败而中止;数据。为什么它到达NULL数组时会给我一个断言错误?
这是我的代码的结构:
typedef struct {
int* data;
unsigned int len;
} intarr_t;
以下是删除具有以下最高索引的元素的函数:
intarr_result_t intarr_pop( intarr_t* ia, int* i )
{
unsigned int len = ia->len;
if (ia == NULL)
{
return INTARR_BADARRAY;
}
else
{
ia->data = realloc(ia->data, (sizeof(int)*(len-1)));
assert (ia->data);
if (ia->data != 0)
{
if (i != 0)
{
*i = ia->data[len-1]
ia->len = len-1;
return INTARR_OK;
}
}
else
{
return INTARR_BADINDEX;
}
}
return 0;
}
答案 0 :(得分:3)
len
被声明为unsigned int
。因此,如果len
等于0,那么行
ia->data = realloc(ia->data, (sizeof(int)*(len-1)));
^ (len-1) underflows if len == 0
将尝试在32位计算机上分配4GB,或在64位计算机上分配大量内存。无论哪种方式,如果分配失败并且realloc
返回NULL
,assert
将失败。
为避免此问题,您需要处理len == 0
作为特例。
答案 1 :(得分:0)
per this link:
<https://www.securecoding.cert.org/confluence/display/seccode/MEM04-C.+Beware+of+zero-length+allocations>
When the requested size is 0,
the behavior of the memory allocation functions malloc(), calloc(), and realloc()
is implementation-defined.
Subclause 7.22.3 of the C Standard [ISO/IEC 9899:2011] states:
If the size of the space requested is zero, the behavior is implementation-defined:
either a null pointer is returned,
or the behavior is as if the size were some nonzero value,
except that the returned pointer shall not be used to access an object.
it seems that your implementation returns NULL when the allocation size is 0