设置下一个指针时,循环链接列表中的C分段错误

时间:2014-04-22 14:01:12

标签: c pointers circular-list

我一直在寻找在C中创建循环链接列表。唯一的问题我不知道为什么这会产生分段错误。从print语句中,程序一直工作,直到设置每个阶段节点中的下一个指针。如果有人可以帮助我,将不胜感激。感谢

typedef struct stage stage;

/* data structure to store stage information */
struct stage
{
    char name[21]; /* stage name */
    stage* next;   /* pointer to next stage */
    int ncoins;    /* number of coins in the stage */
    int npipes;    /* number of pipes in the stage */
};


stage * create_stage(char * line)
{
    char * name; 
    int npipes;
    int ncoins;

    sscanf(line, "%s %d %d",name, &npipes, &ncoins);

    printf("Name: %s NCoins:%d NPipes:%d\n",name, ncoins,npipes);

    stage * s = malloc(sizeof(stage *));
    strncpy(s->name,name,MAX_NAME_LEN);
    s->ncoins = ncoins;
    s->npipes = npipes;

    printf("S Has: Name: %s NCoins:%d NPipes:%d\n",s->name, s->ncoins,s->npipes);


    return s;
}

stage * find_stage(stage * root, char * str)
{
    //Check that root is not null
    if(root == 0){
        return 0;
    }
    //Check the root is equal to the string
    if(strncmp(root->name, str, strlen(str))){
        return root;
    }
    stage * current = root;

    //Check until it has come full circle.
    while(current != root){
        if(strncmp(root->name, str, strlen(str))){
            return current;
        }
        current = current->next;
    }
    //Return nothing 
    return 0;
}


int main(void)
{
    //Game Settings
    char * stage1 = "garden 1 2";
    char * stage2 = "hallway 1 4";
    char * stage3 = "throneroom 2 8";

    printf("Made strings\n");

    //First node of the list
    stage * stg1 = create_stage(stage1);
    stage * stg2 = create_stage(stage2);
    stage * stg3 = create_stage(stage3);

    printf("Created stages\n");

    printf("Stage 1\nName: %s nPipes: %d nCoins: %d\n",stg1->name,stg1->npipes,stg1->ncoins);
    printf("Stage 2\nName: %s nPipes: %d nCoins: %d\n",stg2->name,stg2->npipes,stg2->ncoins);
    printf("Stage 3\nName: %s nPipes: %d nCoins: %d\n",stg3->name,stg3->npipes,stg3->ncoins);

    stg1->next = stg2;
    stg2->next = stg3;
    stg3->next = stg1;

    printf("stages connected");

    stage * foundStage = find_stage(stg1, "throneroom");


    free(stg1);
    free(stg2);
    free(stg3);


    return 0;

}

1 个答案:

答案 0 :(得分:1)

更改

char * name; 

char name[MAX_NAME_LEN] ; 

当您使用sscanf时,name必须指向某事。如果您声明char *name,则无法指定名称。

并更改

stage * s = malloc(sizeof(stage*));

stage * s = malloc(sizeof(stage));

您需要结构stagesizeof(stage))的大小,而不是指向stagesizeof(stage*))的指针的大小。当你使用sizeof(stage*)时,你没有分配足够的内存,那么当你填充新分配的阶段时,你会覆盖不属于你的内存,从那时起你就会得到未定义的行为(任何事情都可能发生)。