int heapSize = 20; //variable
int left(int i) {
return (2 * i) + 1;
}
int right(int i) {
return (2 * i) + 2;
}
void heapify(string arr[], int i) {
int l = left(i);
int great=0;
int r = right(i);
if ( ((strcmp(arr[l].c_str(),arr[i].c_str()))>0) && (l < heapSize)) {
great = l;
}
else {
great = i;
}
if ( ((strcmp(arr[r].c_str(),arr[great].c_str()))>0) && (r < heapSize)) {
great = r;
}
if (great != i) {
string temp = arr[i];
arr[i] = arr[great];
arr[great] = temp;
heapify(arr, great); //Getting segment here
}
}
void BuildMaxHeap(string arr[]) {
for (int i = (heapSize - 1) / 2; i >= 0; i--) {
heapify(arr, i);
}
}
void HeapSort(string arr[]) {
BuildMaxHeap(arr); //
for (int i = heapSize; i > 0; i--) {
string temp = arr[0];
arr[0] = arr[heapSize - 1];
arr[heapSize - 1] = temp;
heapSize = heapSize - 1;
heapify(arr, 0);
}
}
Getting segmentation fault with this string heap sort code for heapSize larger than 15, for example 20 elements.
Any idea about the reason?
I backtraced it in gdb and I get this
#0 0x0038124b in ?? () from /lib/tls/i686/cmov/libc.so.6
#1 0x08048f62 in heapify(std::string*, int) ()
#2 0x08049050 in heapify(std::string*, int) ()
#3 0x080490ae in BuildMaxHeap(std::string*) ()
#4 0x080490d3 in HeapSort(std::string*) ()
#5 0x080494f5 in main ()
So, what is wrong with the heapify function?
In the
ifs you should check if the indexes are in the bounds of the array before you try to compare the stings: