【发布时间】: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