c - C中的段错误

标签 c pointers segmentation-fault

我有以下 C 程序。当我包含以下行时它会起作用,否则会出现段错误:

printf("head(%p), last(%p), newnode(%p)\n", head, last, newnode);

知道这里有什么问题吗?

这是我的整个程序。这是一个基本的循环队列示例。

#include "stdio.h"
#include "malloc.h"

struct node {
    int data;
   struct node *next;
};

typedef struct node NODE;

void display(NODE *);

int main(void) {

    NODE *head, *last, *newnode = NULL;
    int i = 5;

    for ( ; i > 0; i--) {
        newnode = (NODE *) malloc(sizeof(NODE));
        newnode->data = i*10;
        newnode->next = NULL;

        //printf("head(%p), last(%p), newnode(%p)\n", head, last, newnode);


        if (head == NULL) {
            head = newnode;
            last = newnode;
        } else {
           last->next = newnode;
           last = newnode;
        }

        last->next = head;
    }

    display(head);

    return 1;
}

void display(NODE *head) {

    NODE *temp = NULL;
    temp = head;

    printf("Elements --> ");
    do {
            printf("%d ", temp->data);
            temp = temp->next;
    } while (temp != head);

    printf("\n");

}

最佳答案

您还需要将 headlast 显式初始化为 NULL

在您的声明中:

NODE *head, *last, *newnode = NULL;

只有 newnode 被初始化为NULL。因此,稍后在您的 if/else 中,您正在测试/分配给随机内存。

做这样的事情:

NODE *head, *last, *newnode;
head = last = newnode = NULL;

不能假设指针自动初始化为NULL,即使在某些系统上可能是这种情况。声明为 static 的变量是一个异常(exception)。始终将 C 中的变量初始化为合理的值,尤其是指针。

当您访问垃圾内存时,您正在调用 undefined behavior .当您这样做时,您可能会观察到不一致和令人困惑的结果。在您的情况下,添加 printf 似乎 可以解决问题。这会影响您的代码行为的原因取决于实现,并且 - 一旦您引入了未定义的行为 - 就超出了您的控制范围。

关于c - C中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11385786/

相关文章:

python - 在 C 中嵌入 Python - 段错误

C数独回溯求解器预检函数

c - 关于怪异指针的问题

c - Linux 的 dos.h?

c++ - 如何知道某个指针是否已在其他地方释放

c++程序在执行分配内存的函数时崩溃

python - 素数生成器中的段错误

c - 左值需要错误混淆吗?

c - 在c中使用指针覆盖内存的可能性?

c - 段错误和结构