Heap Sort

I am recieving an error that states "HEAP CORRUPTION DETECTED" the app wrote to memory after end of heap buffer. I have looked and looked but with no luck, any help would be appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
void HeapSort(CIntStat *a, int n)
{
	int parent, child = 0;
	CIntStat temp;
	int elementCount = n;
	int i = elementCount / 2;
	while (i > 0)
	{
		parent = i;
	    temp = a[parent];

		while (parent * 2 <= elementCount)
		{
			child = parent * 2;
			if (child != elementCount && a[child] < a[child + 1])
				child++;
			if (temp < a[child])
				a[parent] = a[child];
			else
				break;
			parent = child;
		}
		a[parent] = temp;
		i--;
	}	
	
	while (elementCount > 1)
	{
		temp = a[elementCount];
		a[elementCount] = a[1];
		a[1] = temp;
		elementCount--;
		parent = 1;
		while (parent * 2 <= elementCount)
		{
			child = parent * 2;
			if (child != elementCount && a[child] < a[child + 1])
				child++;
			if (temp < a[child])
				a[parent] = a[child];
			else
				break;
			parent = child;
		}
	a[parent] = temp;
	}
	
}
It would be better if you provide a complete program that demonstrates the problem. With what you have posted nobody has any idea what the function inputs are or what the CIntStat type is.
It's almost impossible to tell for sure without spending a lot of time on it, but you do have the following code with looks problematic:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void HeapSort(CIntStat *a, int n)
{
...

	int elementCount = n;
	int i = elementCount / 2;
	while (i > 0)
	{
		parent = i;
		temp = a[parent];
...
		while (parent * 2 <= elementCount)
		{
...
				a[parent] = a[child];


That's clearly wrong.
N is simply the number of elements while CIntStat can be treated as a normal array since I overloaded operators to do so. kbw, what is wrong in the part?
Last edited on
This is the kind of problem that needs to be debugged. i'm not sure what help anyone can give without a complete example that demonstrates the problem. We need to see the definition of all types as well as a short main function that demonstrates the problem.
a[parent] = a[child]; is an out of bounds access error.
Yeah its a very long program kempo.. i understand for sure. Thanks guys
Topic archived. No new replies allowed.