HEAP CORRUPTION DETECTED

Hello everyone!

i'm trying to implement a merge sort algorithm with the code below, to get myself trained to algorithms and memory allocation. Using Visual Studio 2010, i get the error message :

******************************************************************************
HEAP CORRUPTION DETECTED: after Normal Block(#136) at 0x001E4A88 *
CRT detected that the application wrote to memory after end of heap buffer *
******************************************************************************

Could anyone help ?
Also, i guess i know what a heap is but a not a heap buffer.

Thank you in advance!
regards

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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82

#include <iostream>

using namespace std;

template<typename mtype>
void merge(mtype* a, unsigned int ileft, unsigned int imiddle, unsigned int iright)
{
    unsigned int i=ileft;
    unsigned int j=imiddle;
    unsigned int k=ileft;
    
    mtype* b= new mtype[iright-ileft+1];
    
    while (i<imiddle || j<iright)
    {
        if (i<imiddle && j<iright)
        {
            if (a[i]<a[j])
            {
                b[k]=a[i] ; k++ ; i++; 	   
            }
            else
            {
                b[k]=a[j] ; k++ ; j++; 
            }
        }
        else if (i==imiddle)
        {
            b[k]=a[j] ; k++ ; j++; 
        }
        else if (j==iright)
        {
            b[k]=a[i] ; k++ ; i++;
        }
    }
    
    for (unsigned int d=ileft ; d<iright ; d++)
    {
        a[d]=b[d];
    }
    delete b;
}

template<typename mtype>
void sort(mtype* a, unsigned int n)
{
    for (unsigned int window=1 ; window<n ; window*=2)
    {
	for (unsigned int i=0 ; i < n ; i+=window*2)
	{
	    unsigned int left=i;
	    unsigned int middle=i+window;
	    unsigned int right=i+2*window;
            merge<mtype>(a, left,middle,right);
	}
    }
}

int main()
{
    int a[10];
    
    a[0]=2;
    a[1]=3;
    a[2]=5;
    a[3]=12;
    a[4]=14;
    a[5]=4;
    a[6]=9;
    a[7]=10;
    a[8]=40;
    a[9]=43;

    //merge<int>(a, 0,5,9);
    sort<int>(a,10);
	
    for (unsigned int d=0 ; d<10 ; d++)
    {
        cout << "a[" << d << "]=" << a[d] << endl;
    }    
}
Last edited on
Remove the for loop on line 50. This is done within merge(...).
It will emliminate the heap corruption only...

By the way: You don't need to write explicitely the template parameter when the compiler is able to deduce:
merge(a, left,middle,right);
Topic archived. No new replies allowed.