gpt4 book ai didi

c - realloc 在程序中触发断点

转载 作者:行者123 更新时间:2023-11-30 14:51:32 26 4
gpt4 key购买 nike

我正在尝试制作一个具有“item”对象数组的程序。当程序运行足够长的时间后,它应该执行一些操作,然后将其从数组中删除。然而程序在

处触发了一个断点
    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++ 中的现代容器类正确完成它。避免使用 C 风格指针,避免在堆上分配对象,以及是否必须将 new 与智能指针一起使用。

话虽如此,我在阅读您的代码时发现了两个明显的问题:

itemList = (item *)malloc(itemCount);

您在这里仅分配 1 个字节。

item newItem = itemList[itemCheck];

将 itemList 传递给 realloc 后,您不得访问 itemList。

关于c - realloc 在程序中触发断点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48223576/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com