I'm ultimately trying to use heapsort to alphabetically sort words that have been read in. I've never done heaps before so I'm trying to follow along with my book. I'm using cin to store the words into a dynamically allocated array, as number of words is unknown ahead of time. From separate code I know it is being read in and the array is getting larger correctly. Then I'm trying to heapify this array, but I keep getting a segmentation fault as I'm new to programming, I can't determine how to trace this back to what I did wrong. This is my heapify code:
void Heap::make(){
//make a heap from wordArray
//r = last non-leaf
for(int r = size/2; r > 1; r--){
int c = 2 * r; //location of left child
while(r <= size){ //size is a data member of Heap
//if r has 2 children and right is larger, make c the right child
if((c < size) && (wordArray[c] < wordArray[c+1])){
c++;
}
//fix if parent failed heap-order condition
if(wordArray[r] < wordArray[c]){
swap(wordArray[r], wordArray[c]);
r = c; //check that it didn't get messed up at c
c = 2 * c;
}
else{
break; //heap-order condition holds so stop
}
}
}
}
from playing around with couts I can determine that the program works until the if(wordArray[r] < wordArray[c])
part. The elements of wordArray are stings, and the comparators work correctly from outside testing. Is this something to do with the array being dynamic or something? I'm confused as to what I'm doing wrong here.
You are reading out of bounds. When you check:
where
c
is the last element, you read out of bounds here:The check should be:
And yet another problem is here:
where
r
is used in the code when it is clearly out of bounds if itr == size
.For arrays of size,
n
, their elements go from0 to n-1
, so accessingn
th element is undefined behavior.