realloc在程序中触发断点
我正在尝试制作一个具有“item”对象数组的程序。它应该在程序运行足够长的时间后执行某些操作,然后将其从数组中删除。 但是,程序会在以下位置触发断点:realloc在程序中触发断点,c,crash,realloc,C,Crash,Realloc,我正在尝试制作一个具有“item”对象数组的程序。它应该在程序运行足够长的时间后执行某些操作,然后将其从数组中删除。 但是,程序会在以下位置触发断点: if ((newItemList = (item*)realloc(itemList, newItemCount * sizeof(item))) == NULL) 我不明白为什么 这是我的密码 #include "stdafx.h" #include <iostream> using namespace std; stru
if ((newItemList = (item*)realloc(itemList, newItemCount * sizeof(item))) == NULL)
我不明白为什么
这是我的密码
#include "stdafx.h"
#include <iostream>
using namespace std;
struct item
{
const char *name;
unsigned long time;
bool complete = 0;
};
item *itemList;
unsigned int itemCount = 1;
unsigned long currentTime = 0;
unsigned long lastCheckTime = 0;
int main()
{
itemList = (item *)malloc(itemCount);
if (itemList == NULL)
exit(1);
itemList[0].name = "Item";
itemList[0].time = 15;
itemList[0].complete = 0;
while (1)
{
currentTime += 1;
if (lastCheckTime != currentTime)
{
lastCheckTime = currentTime;
if (itemList == NULL)
{
exit(2);
}
else
{
unsigned int newItemCount = 0;
for (unsigned int itemCheck = 0; itemCheck < itemCount; itemCheck++)
{
if (itemList[itemCheck].time <= currentTime)
{
cout << "Start item " << itemList[itemCheck].name << " scheduled for " << itemList[itemCheck].time << " seconds @ " << currentTime << " seconds" << endl;
itemList[itemCheck].complete = 1;
}
else
{
cout << "Item " << itemList[itemCheck].name << " scheduled for " << itemList[itemCheck].time << " seconds" << endl;
}
}
item *newItemList = NULL;
for (unsigned int itemCheck = 0; itemCheck < itemCount; itemCheck++)
{
if (!itemList[itemCheck].complete)
{
newItemCount++;
if ((newItemList = (item*)realloc(itemList, newItemCount * sizeof(item))) == NULL)
{
exit(3);
}
else
{
item newItem = itemList[itemCheck];
itemList = newItemList;
itemList[newItemCount - 1] = newItem;
}
}
else
{
// cout << "removed item " << itemList[itemCheck].name << " scheduled for " << itemList[itemCheck].time << " seconds" << endl;
}
free(newItemList);
}
itemCount = newItemCount;
}
}
}
return 0;
}
为什么会这样?我做了什么错事?< > P > >代码是C,不是C++。除非这是一种教育性的东西,要学会理解旧的内存管理,扔掉它,然后用C++中的现代容器类来正确地处理它。避免使用C风格的指针,避免在堆上分配对象,如果必须将new与智能指针一起使用 尽管如此,我在阅读代码时发现了两个明显的问题:
itemList = (item *)malloc(itemCount);
您在这里只分配了1个字节
item newItem = itemList[itemCheck];
将itemList传递给realloc后,您不能访问它。使用C样式数组和C样式内存管理有什么特殊原因吗?你可以通过使用C++的构造来避免所有这些。你说“触发断点”是什么意思?我也很确定你在访问它之后,如果它调用了一个ReLoC列表(即使那个调用失败)是UB。不要用C++来编程C。永远不要使用malloc/calloc/realloc/free!无论何时需要rsizable数组,请使用std::vector。
main()
-itemList=(item*)malloc(itemCount)
中的第一个起始元素分配的是itemCount
字节,而不是item
s的数量。随后的赋值itemList[0]。name=“Item”
,itemList[0]。time=15
,和itemList[0]。complete=0
,因此所有赋值都具有未定义的行为(实际上,它们会破坏可能产生任何后果的内存区域)。在某种程度上,这很可能是导致程序在realloc()
item newItem = itemList[itemCheck];