【问题标题】:Why does a stack push cause a segmentation fault?为什么堆栈推送会导致分段错误?
【发布时间】:2018-05-01 16:36:43
【问题描述】:

我的代码实际上是如何给出分段错误的?

我想将TOS 保留为双指针。

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

typedef struct node_tag{
    int num;
    struct node_tag* next;
}NODE;

void push(int x, NODE **TOS){
    NODE* temp = (NODE*) malloc(sizeof(NODE));
    temp->num = x;
    temp->next = (*TOS);
    (*TOS) = temp;
}

int main(){
    NODE **TOS = NULL, *temp;
    printf("<<<Stack Push>>>\n");
    push(0, TOS);
    printf("%i\n", (*TOS)->num);
}

【问题讨论】:

  • 因为您在此代码中取消引用 NULL。
  • NODE **TOS = NULL -> NODE *TOS = NULL, push(0, TOS); -> push(0, &amp;TOS);, printf("%i\n", (*TOS)-&gt;num); -> printf("%i\n", TOS-&gt;num);
  • malloc 返回一个 void 指针,它会自动转换为任何其他类型。不要从malloc 转换返回值,这样做会掩盖编译器可能为您检测到的编码错误。
  • @BakaBaka 如果您的问题已解决,您可以通过单击您认为最有用的答案旁边的复选标记将此问题标记为已解决。

标签: c stack push


【解决方案1】:

你需要这样使用它;

int main(){
    NODE *TOS = NULL, *temp;
    printf("<<<Stack Push>>>\n");
    push(0, &TOS);
    printf("%i\n", TOS->num);
}

【讨论】:

    猜你喜欢
    • 2019-12-08
    • 1970-01-01
    • 2020-07-17
    • 1970-01-01
    • 2011-10-22
    • 1970-01-01
    • 2021-07-18
    • 2020-04-15
    • 1970-01-01
    相关资源
    最近更新 更多