I have implemented a binary heap class in C++ for school. I am having trouble with the program running on the school Linux server. My code outputs 100% correctly on my Mac. It appears to SegFault after the first line of code is printed from the main.cpp. I have tried using GDB and haven't been able to pin point the issue. Running GDB gives me the following issue: Program received signal SIGSEGV, Segmentation fault. 0x00007ffff7ae8d68 in std::string::assign(std::string const&). Any help trying to correct this would be truly appreciated.
EDIT: I figured out it was the insert function causing the issues: I have updated the function to this:
UPDATED Insert Function:
template <class typ>
void Heap<typ>::insert(typ k) {
if (size == 0) {
size = size + 1;
heap[size] = k;
return;
}
if (size == cap-1) {
cap = cap * 2;
typ *tempHeap = new typ [cap];
for (int i = 1; i <= size; i++)
tempHeap[i] = heap[i];
delete [] heap;
heap = tempHeap;
}
size = size + 1;
heap[size] = k; // insert item at end of heap
int i = size; // set i to size
while (i != 1 && heap[parent(i)] > heap[i]) { // move up to parents until heap property is restored all the way to the root
swapKeys(&heap[parent(i)], &heap[i]); // swap items
i = parent(i); // set i to parent of i
}
}
This fixes the segfault that was happening and correctly outputs the heap.