【发布时间】:2018-01-12 09:50:38
【问题描述】:
我正在尝试制作一个包含“项目”对象数组的程序。当程序运行足够长的时间然后将其从数组中删除时,它应该做一些事情。 但是程序会在
处触发断点 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;
}
输出:
Critical error detected c0000374
event.exe has triggered a breakpoint.
The program '[7460] event.exe' has exited with code 0 (0x0).
为什么会这样?我做错了什么?
【问题讨论】:
-
使用 C 风格的数组和 C 风格的内存管理有什么特别的原因吗?你可以通过实际使用 C++ 提供的结构来避免这一切。
-
“触发断点”是什么意思?
-
另外,我很确定您在对其进行 realloc 调用(即使该调用失败)后访问 itemList 是 UB。
-
不要在 C++ 中编写 C。 永远不要使用 malloc/calloc/realloc/free!每当您需要一个可调整大小的数组时,请使用 std::vector。
-
main()-itemList = (item *)malloc(itemCount)中的第一个注视分配itemCount字节,而不是items 的数量。随后的分配itemList[0].name = "Item"、itemList[0].time = 15和itemList[0].complete = 0因此都具有未定义的行为(实际上,它们会破坏一些可能产生任何后果的内存区域)。这很可能是程序失败的原因之一,在某种程度上,realloc()