segmentation fault (core dumped) in C programming

102 Views Asked by At

I am currently studying data structures and algorithms and learning how stacks works.

I wrote a simple C code that shows how the basic functionalities of stacks works including push and pop algorithm which basically process elements into an array. The code wasn't finish yet and I am trying to learn the language and its algorithm as day goes by. To my surprise I've received an error 'segmentation fault (core dumped)' after compiling and it's pretty confusing for me as an individual who is learning how to code.

#include <stdio.h>
#include <string.h>
#define MAXSIZE 100

struct stack
{
  int a[MAXSIZE];
  int Top;
};

/*
 * Add an element to stack
 */
void push(struct stack *pu)
{
  int element;

  printf("element: ");
  scanf(" %d", &element);
  pu->a[pu->Top] = element;

  if(pu->a[pu->Top] >= MAXSIZE -1)
     {
        printf("stack is full\n");
 } else{
        // Prints out the top most element
    printf("Top is: %d\n", pu->a[pu->Top]); 
 }
}

/*
* Pop/Remove an element from the stack
*/
void pop(struct stack *po)
{
  printf("You're in pop function.\n");
     if(po->Top <= -1)
    {
       printf("stack is underflow");
    } else{
       printf("%d will be remove from the stack", po->a[po->Top]);
       printf("%d has been removed from the stack", po->a[po->Top]);
    }
}
void Second(char x[])
{
  struct stack pa;

     if(x[1] == 'u')
    {
           push(&pa);
     } else if(x[1] == 'o'){
       pop(&pa);
     }
}   

int main()
{
  int element;

     char s[MAXSIZE];
     struct stack ps;   
     ps.Top = -1; 

     printf("Push or Pop?\n");
 scanf("%s", &s);

 Second(s);    
}                              
1

There are 1 best solutions below

0
NRagot On

You are accessing an illegal address

To answer your question specifically, the issue is in the function void Second(char[]) : you didn't initialized struct stack pa. pa.Top take some unpredictable value, most likely much too big, and you try to access a memory space not reserved in push when you do pu->a[pu->Top] = element;. Trying to access a memory address not reserved by your process results in a segmentation fault (segfault).

Doing pa->a[99999] = whatever would propably segfault too, because pa->a as a size of 100 as defined in snippet.

Initializing a struct

When declaring a variable, or a struct, such as your stack, you are only declaring that you will need the memory to use that object. But, you do not specifically ask for that memory to be filled with values that makes sens. Usually, that means that the struct is set with whatever data was already in memory from previous use. This is why you should set the fields of your struct to known values as soon as possible. How you do so is a matter of style, I usually make a function dedicated to that named mystruct_ctor (for constructor) or just set everything to zero with struct stack pa = {0} .