Heap stack problem

Hello everyone,

I have a very odd error that crops up in my program. I have a standalone function that instantiates either a die object or a coin object (they are both derived classes) depending on the circumstances; and I allocate memory for whichever object is created. This is then returned as a pointer to the abstract base class. In my main program, I have an algorithm that calls this function through a pointer, either rolls or flips the object many times depending on what was created, and I then represent it visually with a histogram. At then end of the algorithm I use delete on the pointer to the standalone function.

This is where the problem is: whenever 5 coin objects are created there are no problems, the program runs perfectly. There is another case when the program runs perfectly: when 4 coins are created and the fifth object is a die; there are no problems here as well. However, after a die object that is created, rolled, freed in memory; and the program goes through the loop again trying to create a new object (doesn't matter if it's a die or a coin, it does this in both cases), I get a debug error stating that
HEAP CORRUPTION DETECTED: after Normal block (#someSequenceOfNumbers..) at 0xsomeSequenceOfNumbersAndLetters..
CRT detected that the application wrote to memory after end of heap buffer.


If I hit the Ignore option, the program still runs fine and does what it's supposed to do. But I would like to take care of this error. I am guessing that the debugger is seeing that memory is fluctuating and it thinks that this is an error? I'm quite stumped here. Any help would be appreciated!
The program is trying to write to memory that it is not allowed to write to. It just happen to "work". It is hard to say anything more exact without seeing the code.
Last edited on


And I tried using a virtual destructor on aRandomNumber class, and that didn't solve the issue. Sorry for the late reply..just got out of a final!
Last edited on
Sorry for the double post...but I am wondering. Do you think I should create two separate pointers here, such as:
1
2
3
4
5
6
7
8
if (result == 0)
	{
		aRandomNumberPtr = new aCoin(0, 1);
	}
	else
	{
		aRandomNumberPtr = new aDie(1, 6);
	}


For example, I would create:

1
2
3
4
5
6
7
8
9
10
if (result == 0)
	{
                aCoin *coin = new aCoin(0,1);
		aRandomNumberPtr = coin;
	}
	else
	{
		aDie *die = new aDie(1, 6);
                aRandomNumberPtr = die;
	}


But, now that I think about it, this seems redundant as that is what polymorphism is about. I am genuinely stumped here. I don't see why it is causing a problem.

This problem only occurs in Visual Studio 2010..It doesn't occur in Dev-C++
Yes you can do do like that. It will be the same.
Topic archived. No new replies allowed.