【问题标题】:Running onto the Online compiler but giving seg fault on terminal(Ubuntu)运行到在线编译器但在终端上出现段错误(Ubuntu)
【发布时间】:2016-04-28 03:40:39
【问题描述】:

我的程序编译成功,但是当我在 linux 系统上运行此代码时,它给了我分段错误,但是当我在在线编译器 Ideone 上执行相同的代码时,它给了我正确的输出。下面是代码。

为什么会这样,任何人都可以解释,如果代码中有任何问题,请提出正确的解决方案。
谢谢

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

int MAX_SIZE=21;

struct node;
typedef struct node NODE;
typedef NODE *link;

struct node{
   int data;
   link next;
};

typedef struct{
   link head;
   int top;
}Stack;

Stack createStack(Stack s){
   s.head = NULL;
   s.top = 0;
   return s;
}

link createNode(link n,int data){
   n = (link)malloc(sizeof(NODE));
   n->data = data;
   n->next = NULL;
   return n;
}

Stack push(Stack s,int data){
   if(s.top < MAX_SIZE){
      link newNode = createNode(newNode,data);    
      if(s.head == NULL){
         s.head = newNode;
      }else{
         newNode->next = s.head;
         s.head = newNode;
      }
      s.top++;
   }else{
      printf("Overflow\n");
   }

   return s;
}

Stack pop(Stack s){
   link temp = s.head; 
   if(s.top == 0){
      printf("Underflow\n");
   }else{
      s.head = s.head->next;
      s.top--;
      free(temp);
   }
   return s;
}

void printStack(Stack s){
   link temp = s.head;
   while(temp->next){
      printf("%d -> ",temp->data);
      temp = temp->next;
   }
   printf("%d\n",temp->data);
}

int main(void){
   Stack s;
   s = push(s,5);
   s = push(s,7);
   s = push(s,9);
   s = push(s,11);
   printf("%d\t",s.top);
   printf("%d",s.head->next->next->data);
   printStack(s);
   s = pop(s);
   printStack(s);
   return 0;
}

【问题讨论】:

  • 不是你的问题的原因,但在createNode(link n, ...) 你永远不会对调用者提供的n 做任何事情......所以完全摆脱它作为一个参数。
  • 另外,您的push() 函数不会修改它接收到的s 参数,因此s = push(s, ...); 没有理由使用任何返回值。制作函数void
  • 可能是您的问题的原因:未定义的行为。你在使用之前没有初始化Stack s,所以它从垃圾数据开始。我敢打赌你打算使用写得不好的createStack() 函数。 (写得不好,因为像push()pop(),它有一个无用的返回值。)
  • 1) 不要typedef指针!这会混淆语义,导致混淆并禁止某些用途。 2) 不要将malloc & friends 的结果投射到 C 中!
  • 编译时,始终启用所有警告,然后修复这些警告。 (对于gcc,至少使用:-Wall -Wextra -pedantic(我也使用-Wconversion -std=c99)这会告诉你代码中未初始化变量的使用问题。

标签: c segmentation-fault stack ubuntu-14.04


【解决方案1】:

@mah 的评论在现场。

Stack s在使用前没有初始化,所以一开始是垃圾数据。

这会导致未定义的行为。

行后

Stack s;

添加

s = createStack(s);

另外,在push 中,替换

link newNode = createNode(newNode,data);    

通过

link newNode = NULL;
newNode = createNode(newNode,data);    

我的编译器抱怨在调用中使用了未初始化的 newNode 值。

【讨论】:

    猜你喜欢
    • 2017-09-30
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-06
    • 1970-01-01
    • 2016-07-09
    • 2016-06-18
    相关资源
    最近更新 更多