简体   繁体   English

C程序错误-分段错误(核心已转储)

[英]C program Error - Segmentation fault (core dumped)

I wanted to practice linked lists and so created a small program that would create a linked list. 我想练习链表,因此创建了一个小程序来创建链表。 The program compiles fine using gcc but when i run the program, it works fine till line 13 in main() (scanf("%d", &value1)) after which it prints the error message - "segmentation fault (core dumped)". 该程序可以使用gcc很好地编译,但是当我运行该程序时,它可以正常运行,直到main()的第13行(scanf(“%d”,&value1))之后,它会显示错误消息-“分段错误(核心已转储)” 。 I added a print statement in my own testing after line 13 and it doesn't get printed (hence my assumption that the problem arrises after scanf which I dont know why). 我在第13行之后的自己的测试中添加了一条打印语句,但它没有被打印出来(因此,我认为问题会在scanf之后出现,我不知道为什么)。

So what am I doing wrong? 那我在做什么错?

// Creates n numbers of nodes in a linked list where n is the argument 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_NAME_LEN 25

typedef struct fruits {
    char *name;
    int price;
    struct fruits *next;
}fruits;

int check_format(int argc, char **argv);
fruits *create_node(char name[MAX_NAME_LEN], int value);
void print_nodes(fruits *head);

int check_format(int argc, char **argv) {

    if (argc == 2) {
        int argument = atoi(argv[1]);
        if (argument > 0) {
            return 1;
        } else {
            return 0;
        }
    } else {
        return 0;
    }
}

fruits *create_node(char name[MAX_NAME_LEN], int value) {

    fruits *newNode = malloc(sizeof(fruits));
    strcpy(newNode->name, name);
    newNode->price = value;
    newNode->next = NULL;

    return newNode;
}

void print_nodes(fruits *head) {

    fruits * curr = head;
    while (curr != NULL) {
        printf("%s is %d\n", head->name, head->price);
        curr = curr->next;
    }
}

int main(int argc, char **argv) {

    int valid_format = check_format(argc, argv);

    fruits *curr = NULL;
    fruits *head = curr;
    if (valid_format) {
        int number_of_nodes;
        char fruitName[MAX_NAME_LEN] = {""};
        int value1 = 0;

        number_of_nodes = atoi(argv[1]);
        while (number_of_nodes) {

            printf("Enter the fruit name: ");
            scanf("%s", fruitName);

            printf("Enter the fruit price: ");
            scanf("%d", &value1);

            curr = create_node(fruitName, value1);
            curr = curr->next;
            number_of_nodes--;
        }
    } else {
        fprintf(stderr, "%s", "Usage: ./linked_lists [non-negative integer greater than 0]\n");
    }
    print_nodes(head);
    return 0;
}

You are getting segmentation fault because you are accessing newNode->name pointer without allocating memory to it in create_node() : 由于您正在访问newNode->name指针而不在create_node()为其分配内存,因此您遇到了分段错误:

    strcpy(newNode->name, name);

Allocate memory to newNode->name and then copy name to it: 将内存分配给newNode->name ,然后将name复制到其中:

newNode->name = malloc(MAX_NAME_LEN);
if (newNode->name == NULL)
    exit (EXIT_FAILURE);

strcpy(newNode->name, name);

With this, make sure to free the memory allocated to name pointer before freeing the node. 这样,请确保在释放节点之前释放分配给name指针的内存。

As an alternative, you can have name as char array instead of pointer in structure fruits : 或者,您可以将namechar数组,而不是结构fruits的指针:

typedef struct fruits {
    char name[MAX_NAME_LEN];
    ....
    .... 

With this, you don't need separately allocate/deallocate memory to name . 这样,您就不需要分别为name分配/取消分配内存。


Additional: 额外:

Follow good programming practice, always check the malloc return: 遵循良好的编程习惯,请始终检查malloc返回:

fruits *newNode = malloc(sizeof(fruits));
if (newNode == NULL)
    exit (EXIT_FAILURE);
.....
.....

Make sure to free the dynamically allocated memory once you are done with it. 完成后,请确保释放动态分配的内存。 I do not see any where you are freeing the list nodes after printing them. 在打印列表节点后,我看不到要释放列表节点的任何位置。

fruits *create_node(char name[MAX_NAME_LEN], int value)
{
    fruits *newNode = malloc(sizeof(fruits));
    strcpy(newNode->name, name);
    newNode->price = value;
    newNode->next = NULL;

    return newNode;
}

Here you allocate memory for the struct but not for the name. 在这里,您为结构分配内存,但没有为名称分配内存。 You have to either allocate memory for the name or change the type from pointer to a fixed size array: 您必须为名称分配内存或将类型从指针更改为固定大小的数组:

typedef struct fruits 
{
    char name[MAX_NAME_LEN];
    int price;
    struct fruits *next;
}fruits;

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

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