Reputation: 169
I am trying to make a program that has an array of 'item' objects. It is supposed to do something when the program has run for enough time and then remove it from the array. However the program triggers a breakpoint at
if ((newItemList = (item*)realloc(itemList, newItemCount * sizeof(item))) == NULL)
and I don't understand why?
Here is my code
#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;
}
Output:
Critical error detected c0000374
event.exe has triggered a breakpoint.
The program '[7460] event.exe' has exited with code 0 (0x0).
Why is this happening? What am I doing wrong?
Upvotes: 0
Views: 444
Reputation: 8598
That code is C, not C++. Except if this is some kind of educational thing to learn to understand old-style memory management, throw that away and do it properly with modern container classes in C++. Avoid C style pointers, avoid allocating objects on the heap, and if you must use new with smart pointers.
That being said, there were two obvious issues I found while reading your code:
itemList = (item *)malloc(itemCount);
You are only allocating 1 byte here.
item newItem = itemList[itemCheck];
You must not access itemList after you have passed it to realloc.
Upvotes: 1