2017-01-03 1 views
-1

내가 배열을 사용하여 스택을 구현하기 위해 노력하고, 나는,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을 사용하고 있습니다.

+1

당신은 당신은 포인터'stack'을 선언하지만, 당신이 그것에 어떤 메모리를 할당 않았다 –

+2

스택 포인터에 대한 메모리를 할당하지 않았다? 나는 할당이 이루어지고있는 것을 볼 수 없다. 왜 단순히 스택 구조가 아닌가? –

+1

초기화되지 않은 로컬 (비 정적) 변수에는 * indeterminate * 값이 있습니다. 초기화되지 않은 포인터를 역 참조하면 * 정의되지 않은 동작이 발생할 수 있습니다. –

답변

2

초기화하기 전에 stack을 사용 중입니다. 당신이 원하는 :

stackstructure *stack = malloc(sizeof(stackstructure)); 
+0

초기화하는 방법 그 코드에서 뭐가 잘못 되었습니까? – user123456987

+1

아니면'stackstructure stack = {0}; 대신'stackstructure * stack;'을 사용하십시오. – alk

3

당신이 경고를 사용하도록 설정 한 경우, 컴파일러는 잘못 무엇을 말할 것 :

warning: variable 'stack' is uninitialized when used here [-Wuninitialized] 
    stack->top = -1; 
    ^~~~~ 

당신은 변수 stack를 초기화하지 않은하지만 stack->top = -1;에 액세스하려고합니다. 그러면 segfault를 설명하는 정의되지 않은 동작이 호출됩니다.

당신을 가리 키도록 stack에 대한 stackstructure을 할당 할 수 있습니다, fflush(stdin);이 정의되지 않은 동작이 또한

stackstructure *stack = malloc(sizeof(stackstructure)); 

입니다, 참조 : Using fflush(stdin)


또한, scanf("%c", &ch); 읽을 것 여전히 입력 버퍼에있는 개행 문자. scanf 스킵 공백을 만들려면, % 앞에 공백을 추가

scanf(" %c", &ch); 
+0

'fflush (stdin)'줄을 제거하면 프로그램은 부적절하게 종료 – user123456987

+1

@ user123456987 수정 사항을 확인하십시오. – emlai

0

사용자,

가 액세스하기 전에 포인터를 초기화하십시오. 포인터 변수를 초기화하지 않고 포인터 변수를 사용하는 것은 현명하지 않습니다.

다음과 같이 스택을 초기화하십시오. 초기화 후 나는 엘리먼트를 밀고 팝 할 수 있었다. 시도해보고 다시 확인하십시오. 고마워, 안부.

stackstructure *stack=malloc(sizeof(stackstructure));