繁体   English   中英

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

[英]Segmentation fault when accessing elements of pointer

#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永远不会是=&heap [0];。 但是,我以为我可以用'->'访问指向的结构部分?

对其进行更多编辑后,似乎只有在达到testFraction->分母时才出现段错误。 如果我仅检查分母,它仍然存在段错误,但仅适用于分子。

问题在于,并非所有通过new_frac()代码路径实际上都返回一个值。 然后,您可以通过可能未初始化的指针进行分配:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM