2013-04-10 42 views
-1
#include <stdio.h> 
#include <stdlib.h> 
#include "frac_heap.h" 

#define ARRAYSIZE 10 
#define ENDOFARRAY 999 

fraction heap[ARRAYSIZE] = {0}; 
block freeBlocks[ARRAYSIZE] = {0}; 
int startingBlock = 0; 
int nextFree = 0; 
fraction* fracPointers[][ARRAYSIZE] = {0}; 
block* blockPointers[][ARRAYSIZE] = {0}; 

void init_Heap(){ 
    int x; 
    for(x = 0; x < ARRAYSIZE; x ++){  
     block *currBlock = &freeBlocks[x]; 
     currBlock->isFree = 1; 
     fraction *fractionPointer = &heap[x]; 
     if(x<ARRAYSIZE - 1){ 
      fractionPointer->denominator = x+1; 
     } 
     else if(x == ARRAYSIZE - 1){ 
      fractionPointer->denominator = ENDOFARRAY; 
     } 
    } 
} 

void dump_heap(){ 
    int x; 
    for(x = 0; x < ARRAYSIZE; x ++){ 
     fraction* tempFrac = &heap[x]; 
     printf("%d\t%d\t%d\n",tempFrac->sign, tempFrac->numerator, tempFrac->denominator); 
    } 
} 

fraction* new_frac(){ 

    fraction* testFraction = &heap[0]; 
    if(testFraction->numerator == 0 && testFraction ->denominator==0){ 
     printf("Before return");   
     return testFraction; 
    } 
} 

int main(){ 

    init_Heap(); 
    dump_heap(); 
    fraction *p1; 
    p1 = new_frac(); 
    p1->sign = -1; 
    p1->numerator = 2; 
    p1->denominator = 3; 
    dump_heap(); 
    } 

嘗試調用new_frac()時出現段錯誤。在這一點上,我只是測試代碼,我意識到,測試不會總是= & heap [0] ;.但是,我認爲我能夠訪問我指向' - >'的結構部分?訪問指針元素時出現分段錯誤

編輯一些後,它似乎只有在達到testFraction->分母時纔出現segfault。如果我只檢查分母它仍然是段錯誤,但它只用分子就可以正常工作。

+0

您必須分配內存。 c中的內存管理不是默認的 – 2013-04-10 06:59:02

+1

當你遇到崩潰時(比如分段錯誤),你的第一反應應該是在調試器中運行程序。它會告訴你到底發生了什麼事情,讓你看到調用堆棧,這樣你就知道你是如何在那裏結束的(如果崩潰發生在系統函數中,可以返回到你的代碼),還可以讓你檢查變量幫助你找出可能導致事故的原因。 – 2013-04-10 07:00:34

+0

對,但如果我將其更改爲if(testFraction-> numerator == 0),它將起作用。但是,如果我將其更改爲if(testFraction-> denominator == 0),它會出現段錯誤 – user2252004 2013-04-10 07:00:36

回答

3

問題是,並非所有通過new_frac()的代碼路徑實際上都會返回一個值。然後您繼續通過此可能未初始化的指針進行分配:

p1 = new_frac(); 
p1->sign = -1; 
p1->numerator = 2; 
p1->denominator = 3;