簡體   English   中英

從頭開始編寫 heapify 函數,獲得“基於堆棧的緩沖區溢出”

[英]Writing heapify function from scratch, getting a “stack-based buffer overrun”

我第一次嘗試實現堆排序算法,但是我在使用 heapify 函數時遇到錯誤。

Unhandled exception at 0x0005369A in heapify.exe: Stack cookie instrumentation code detected a stack-based buffer overrun.

控制台確實打開了,輸出是999 10 5 11 1012398875 2 0 1

有人能幫我理解這里出了什么問題嗎? 謝謝你。

#include <iostream>

// given the address of element 0 of an array, and a non-zero index k, heapify assumes that the L/R subtrees
// of node k are max heaps. But the subtrees combined with node k do not necesarily form 
// a max heap. heapify interchanges the value at node k with the value of one of its children,
// and then calls itself on the subtree in question 
int heapify(int* n, int k, int sizeOfHeap)
{
    // terminate the function if the input "node" is not actually a node
    if (k > sizeOfHeap)
    {
        return 0;
    }
        int root = *(n + k); // value of kth node
        int leftChild = *(n + 2 * k); // value of left chold
        int rightChild = *(n + 2 * k + 1); // value of right child
        if (root < leftChild)
        {
            // swap value of kth node with value of its left child
            int temp = root;
            *(n + k) = leftChild;
            *(n + 2 * k) = root;

            // call heapify on the left child
            heapify(n, 2 * k, sizeOfHeap);
        }
        else
        {
            // swap value of kth node with value of its right child
            int temp = root;
            *(n + k) = rightChild;
            *(n + 2 * k + 1) = root;

            // call heapify on right child
            heapify(n, 2 * k + 1, sizeOfHeap);
        }
    
}

int main()
{
    // arr is the array we will heapify. 999 is just a placeholder. 
    // The actual (almost) heap occupies indices 1 - 7
    int arr[8] = {999, 3, 10, 11, 5, 2, 0, 1};
    int sizeOfHeap = 8;
    
    heapify(arr, 1, sizeOfHeap);

    // print out arr
    int i;
    for (i = 0; i <= 7; i++)
    {
        std::cout << arr[i] << std::endl;
    }
}
 

Unhandled exception at 0x0005369A in heapify.exe: Stack cookie instrumentation code detected a stack-based buffer overrun.

控制台確實打開了,輸出是 999 10 5 11 1012398875 2 0 1。

有人能幫我理解這里出了什么問題嗎? 謝謝你。

進程堆棧堆棧數據結構的實際用途之一,FILO 隊列)是內存中用於靜態分配的地方。 對於所有進程,始終很小且大小基本相同。 在堆棧上,編譯器仍然保存局部變量,即小的靜態分配的緩沖區(發生這種情況時,在 Linux 上,堆棧指針被移動以擴展堆棧大小,編譯器評估堆棧上的偏移量)。 它們(緩沖區)無法正確處理(不安全的庫函數,例如strcpy() ),因此它們可能會溢出(溢出),從而導致緩沖區溢出漏洞。

Stack cookie AKA stack canary 是一種緩解技術,用於在攻擊者嘗試利用堆棧緩沖區溢出等漏洞時在堆棧上寫入順序數據,但不限於(如果您將堆棧從堆轉回堆但嚴重覆蓋保存的指令指針......沒關系;) )。 如果檢測到溢出,則它們會引發 SegFault。 示例鏈接與利用示例。

這回答了您的直接問題(了解出了什么問題)。

現在,您應該對其進行調試,然后縮小問題的范圍。 特別是問下一個問題,不再編輯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM