相同的代码 - "分段错误(代码转储)" GCC 4.8.3中的错误,但它在GCC 4.9.2中完美运行

时间:2015-01-31 07:04:07

标签: c++ gcc heap

遵循堆代码,抛出&#34;分段错误(代码转储)&#34; GCC 4.8.3中的错误,但它在GCC 4.9.2中完美运行。 此外,如果我在heapify函数中添加一个简单的cout << "";(在前4-5行中的任何位置),它也可以在GCC 4.8.3中完美地工作。我真的很困惑。怎么会发生这种情况?

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;

int length = 10;

void swap(int a, int b, int* heap)
{
    int tmp = heap[a];
    heap[a] = heap[b];
    heap[b] = tmp;
}

void printHeap(int *heap)
{
    cout << "\n";
    for(int i = 0; i < length; i++)
    {
        cout << heap[i] << " ";
    }
}

void heapify(int *heap, int element)
{
    int leftChild = (2 * element) +1;
    int rightChild = (2 * element) +1+1;
    bool flag = false;
    int swapWith;
        if(leftChild < length && heap[element] > heap[leftChild])
        {
            swapWith = leftChild;
            flag = true;
        }
        if(rightChild < length && heap[swapWith] > heap[rightChild])
        {
            swapWith = rightChild;
            flag = true;
        }
        if(flag)
        {
            swap(element, swapWith, heap);
            heapify(heap, swapWith);
        }
}

void deleteMin(int *heap)
{
    heap[0] = heap[length-1]; //replace last element with the first element[that you want to delete]
    length--;   //reduce the array's length by 1

    heapify(heap, 0);
    printHeap(heap);
}

int main()
{
    int *heap = (int *)malloc(sizeof(int) * length);
    heap[0] = 2;
    heap[1] = 3;
    heap[2] = 6;
    heap[3] = 8;
    heap[4] = 4;
    heap[5] = 7;
    heap[6] = 11;
    heap[7] = 20;
    heap[8] = 15;
    heap[9] = 13;

    heap[0] = 19;
    heapify(heap, 0);
    printHeap(heap);

    deleteMin(heap);
    return 0;
}

在GCC 4.9.2中没有cout语句的工作代码here

0 个答案:

没有答案