내가 배열을 사용하여 스택을 구현하기 위해 노력하고, 나는,SIGSEGV, C
프로그램 신호 SIGSEGV를받은 분할 오류를 얻고있는 분할 오류. main()의 stack_as_array.c에있는 0x00000000004016c1 : 62 62 stack-> top = -1;
내가 SIGSEGV
것을 발견 몇 가지 검색을 수행에 stack_as_array.c
/*
In this following code stack is implemented using an array
*/
//header files
#include <stdio.h>
#include <stdlib.h>
//Define the size of the stack
#define SIZE 10
//Create structure for stack
struct stackasarray{
int top; //here top represents the top of the stack
int stackarray[SIZE]; //this array will act as stack
};
typedef struct stackasarray stackstructure;
//function to check if stack is empty
int stackempty(stackstructure *stack){
return (stack->top == -1);
}
//function to check if stack is full
int stackfull(stackstructure *stack){
return (stack->top == SIZE - 1);
}
//function to push data into stack
void push(stackstructure *stack, int data){
stack->top++;
stack->stackarray[stack->top] = data;
return;
}
//function to pop top of the stack from the stack
int pop(stackstructure *stack){
int topofstack = stack->stackarray[stack->top];
stack->top--;
return topofstack;
}
//function to peek at stack
int peek(stackstructure *stack){
return (stack->stackarray[stack->top]);
}
//function to display stack
void display(stackstructure *stack){
for(int i = 0; i < stack->top; i++){
printf("%i ", stack->stackarray[stack->top]);
}
return;
}
int main(){
int choice, data;
char ch;
//declare a pointer variable to the structure(stack)
stackstructure *stack;
//initialize the stack with top points to NULL(-1)
stack->top = -1;
do{
//Menu for the stimulation of stack
printf("Menu\n1.Push\n2.Pop\n3.Peek\n4.Display\n5.Exit\nEnter your choice:");
scanf("%i", &choice);
switch(choice){
case 1: if(stackfull(stack)){
printf("Stack is full! Overflow");
}
else{
printf("Enter the data to be pushed: ");
scanf("%i", &data);
push(stack, data);
}
break;
case 2: if(stackempty(stack)){
printf("Stack is empty! Underflow");
}
else{
data = pop(stack);
printf("%i is poped from stack.", data);
}
break;
case 3: if(stackempty(stack)){
printf("Stack is empty! Nothing to peek.");
}
else{
data = peek(stack);
printf("%i is at the top of the stack.", data);
}
break;
case 4: if(stackempty(stack)){
printf("Stack is empty!");
}
else{
display(stack);
}
break;
case 5: printf("\nExiting");
exit(0);
}
printf("Do you want to continue ?");
fflush(stdin);
scanf("%c", &ch);
}while(ch == 'y' || ch == 'Y');
return 0;
}
가 발생 할 때를 nullpointer 또는 초기화되지 않은 포인터 역 참조.
하지만 문제를 해결할 수 없습니다. 내가 뭘 잘못하고있어?
윈도우 머신에서 gcc (x86_64-posix-seh, MinGW-W64 프로젝트로 빌드) 6.1.0을 사용하고 있습니다.
당신은 당신은 포인터'stack'을 선언하지만, 당신이 그것에 어떤 메모리를 할당 않았다 –
스택 포인터에 대한 메모리를 할당하지 않았다? 나는 할당이 이루어지고있는 것을 볼 수 없다. 왜 단순히 스택 구조가 아닌가? –
초기화되지 않은 로컬 (비 정적) 변수에는 * indeterminate * 값이 있습니다. 초기화되지 않은 포인터를 역 참조하면 * 정의되지 않은 동작이 발생할 수 있습니다. –