访问指针元素时出现分段错误

时间:2013-04-10 06:56:42

标签: c pointers

#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()时出现分段错误。此时我只是测试代码,我意识到testfraction不会总是=&amp; heap [0] ;.但是,我以为我能够通过“ - &gt;”访问我指向的结构部分?

在编辑了一些之后,它似乎只有在达到testFraction-&gt;分母时才会出现段错误。如果我只检查分母,它仍然是段错误,但它只与分子一起正常工作。

1 个答案:

答案 0 :(得分:3)

问题是并非所有通过new_frac()的代码路径都会返回一个值。然后,您继续通过这个可能未初始化的指针进行分配:

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