C - No output in the program - c

I made a stack and i am using the isEmpty function but the output is not coming. I trued manually using the gcc command and also using the code runner extension.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
typedef struct Stack
{
int top;
int size;
int *arr;
} Stack;
int isEmpty(Stack *st)
{
if (st->top == -1)
{
return 1;
}
else
{
return -1;
}
}
int main()
{
Stack *st;
st->top = -1;
st->size = 10;
st->arr = (int *)malloc(st->size * sizeof(int));
int i = isEmpty(st);
if (i == 1)
{
printf("The stack is empty\n");
}
else
{
printf("The stack is not empty\n");
}
return 0;
}
The file is named Stack.c.
There is one more thing that the basic hello world program is working perfectly

Stack *st;
st->top = -1;
You invoked undefined behavior by accessing uninitialized pointer st->top = -1;.
You should initialize st first:
Stack *st = malloc(sizeof(Stack));

Related

Segmentation fault while implementing stack as an array

This is a menu-driven program that carries out basic stack operations using arrays in the C programming language. The functions that are performed are push, pop, peep,isempty and isfull.
#include<stdio.h>
#include<stdlib.h>
struct stack
{
long int top;
long int size;
char* key;
};
int is_empty(struct stack *s) //check if its empty
{
if(s->top==-1)
{
return -1;
}
else
{
return 1;
}
}
int is_full(struct stack *s) //check if its full
{
if (s->top ==s->size-1)
{
return -1;
}
else
{
return 1;
}
}
void push(struct stack *s, char x) //pushes into stack
{
int check;
check = is_full(s);
if(check==-1)
{
printf("-1\n");
}
else
{
s->top = s->top+1;
s->key[s->top]=x;
}
}
void pop(struct stack *s) //deletes the last element
{
int check;
check = is_empty(s);
if(check==-1)
{
printf("-1\n");
}
else
{
char k;
k = s->key[s->top];
printf("%c\n",k);
s->top--;
}
}
void peep(struct stack *s) //prints the last element without deleting
{ int check;
char k;
check = is_empty(s);
if (check == -1)
{
printf("-1\n");
}
else
{
k = s->key[s->top];
printf("%c \n",k);
}
}
int main()
{
char ch;
char x;
long int n;
struct stack *s;
scanf("%ld ", &n);
s->size = n; //initialise the size
s->top = -1; //setting as -1 base case
s->key= (char *)malloc(n*sizeof(char)); //dynamic allocation of keys
while(1)
{
scanf("%c ",&ch);
switch(ch)
{
case 'i':
scanf("%c ",&x);
push(s,x);
break;
case 'd':pop(s);
break;
case 'p':peep(s);
break;
case 't':exit(0); //termination case
}
}
return 0;
}
This is a C program that is working for me in some online compilers but in VScode and other compilers, it's showing a segmentation fault without any output. This is an implementation of stack using arrays. Is it a problem with any of the scanf functions?
You have created a pointer variable s and then access the size field on that struct.
struct stack *s;
scanf("%ld ", &n);
s->size = n; //initialise the size
Except s doesn't actually point to anything at this point. You need to either statically or dynamically allocate memory for that struct.
struct stack s;
Or:
struct stack *s = malloc(sizeof(struct stack));

memory allocation to stack pointer

my code is not working but when I change struct stack *sp; to struct stack * sp = (struct stack *) malloc(sizeof(struct stack)); it start working. I am confused in when to allocate memory in heap to struct stack *ptr and when to not. It will be better if u can give me an example when struct stack *ptr can be used and when to use struct stack * sp = (struct stack *) malloc(sizeof(struct stack));
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stack
{
int size;
int top;
char *arr;
};
int stackTop(struct stack* sp){
return sp->arr[sp->top];
}
int isEmpty(struct stack *ptr)
{
if (ptr->top == -1)
{
return 1;
}
else
{
return 0;
}
}
int isFull(struct stack *ptr)
{
if (ptr->top == ptr->size - 1)
{
return 1;
}
else
{
return 0;
}
}
void push(struct stack* ptr, char val){
if(isFull(ptr)){
printf("Stack Overflow! Cannot push %d to the stack\n", val);
}
else{
ptr->top++;
ptr->arr[ptr->top] = val;
}
}
char pop(struct stack* ptr){
if(isEmpty(ptr)){
printf("Stack Underflow! Cannot pop from the stack\n");
return -1;
}
else{
char val = ptr->arr[ptr->top];
ptr->top--;
return val;
}
}
int precedence(char ch){
if(ch == '*' || ch=='/')
return 3;
else if(ch == '+' || ch=='-')
return 2;
else
return 0;
}
int isOperator(char ch){
if(ch=='+' || ch=='-' ||ch=='*' || ch=='/')
return 1;
else
return 0;
}
char* infixToPostfix(char* infix){
struct stack *sp;
sp->size = 10;
sp->top = -1;
sp->arr = (char *) malloc(sp->size * sizeof(char));
char * postfix = (char *) malloc((strlen(infix)+1) * sizeof(char));
int i=0; // Track infix traversal
int j = 0; // Track postfix addition
while (infix[i]!='\0')
{
if(!isOperator(infix[i])){
postfix[j] = infix[i];
j++;
i++;
}
else{
if(precedence(infix[i])> precedence(stackTop(sp))){
push(sp, infix[i]);
i++;
}
else{
postfix[j] = pop(sp);
j++;
}
}
}
while (!isEmpty(sp))
{
postfix[j] = pop(sp);
j++;
}
postfix[j] = '\0';
return postfix;
}
int main()
{
char * infix = "x-y/z-k*d";
printf("postfix is %s", infixToPostfix(infix));
return 0;
}
Two things to always remember when working with pointers in C:
Memory allocation is your problem. You have to think about the allocation of the memory which a pointer variable points to.
You have to be clear in your mind about the distinction between the pointer versus the data that it points to.
So when you say
struct stack *sp;
that will never work, all by itself. It won't work for a program that's implementing a stack, and it won't work for a program that's implementing any other kind of data structure.
When you write
struct stack *sp;
there is one important thing that you have done, and there is one important thing that you have not done.
The compiler allocates space to store one pointer. This pointer is known as sp. But:
The value of this pointer is indeterminate, which means that it does not point anywhere yet. You can't actually use the pointer variable sp for anything. (Yet.)
Or, in other words, going back to the distinction I mentioned earlier, you have taken care of the pointer but you don't have any data that the pointer points to.
But when you say
sp = malloc(sizeof(struct stack));
(and assuming malloc succeeds), now sp points somewhere: it points to a chunk of properly-allocated memory sufficient to hold one struct stack.

I have problems implementing a stack

I have a question about my piece of code here: I tried to write a function, its name is take, the function can get only one int parameter and have to return back the middle number that was inserted. The function has to use in, as minimum memory as possible. I tried to use in a stack. Its my implementation. The problem is that the program doesn't return a value after the third insertion.
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
int take (int);
typedef struct stack
{
int num;
struct stack *next;
}stack;
stack first;
bool isit = true;
int counter = -1;
int main()
{
printf("%d",take(5));
printf("%d", take(6));
printf("%d", take(7));
return 0;
}
int take(int value)
{
if (isit)
{
isit = false;
first.num = value;
first.next = NULL;
}
else
{
static stack newone;
newone.num = value;
newone.next = NULL;
stack temp = first;
while (temp.next != NULL)
{
temp = *temp.next;
}
temp.next = &newone;
}
stack *temp1 = malloc(sizeof(stack));
*temp1 = first;
counter++;
if (counter > 1 && counter % 2 == 0)
{
temp1 = temp1->next;
}
return (temp1->num);
}
A big problem in your code is that you use global variables where you don't need
them. This creates problems that don't expect, like this:
int take(int value)
{
...
static stack newone;
newone.num = value;
newone.next = NULL;
stack temp = first;
while (temp.next != NULL)
{
temp = *temp.next;
}
temp.next = &newone;
The static stack newone is a static variable, it means it will be always the
same every time you call take, you are overwriting the values all the time,
specially the next pointer.
For this reason, avoid using global variables when you can perfectly declare
them in the main function and pass them to the other functions.
Also you malloc part doesn't make any sense. You want minimal memory footprint
but you allocate memory which is lost after temp1 = temp1->next;.
If you want a minimal memory footprint and not having to allocate memory with
malloc, then you can declare an array of fixed length and use it as a stack,
something like this:
typedef struct stack
{
int stack[20];
size_t len;
size_t size;
} Stack;
void stack_init(Stack *stack)
{
if(stack == NULL)
return;
stack->size = sizeof stack->stack / sizeof stack->stack[0];
stack->len = 0;
}
int stack_is_empty(Stack *stack)
{
if(stack == NULL)
return 1;
return stack->len == 0;
}
int stack_is_full(Stack *stack)
{
if(stack == NULL)
return 0;
return stack->len == stack->size;
}
int stack_push(Stack *stack, int value)
{
if(stack == NULL)
return 0;
if(stack_is_full(stack))
return 0;
stack->stack[stack->len++] = value;
return 1;
}
int stack_pop(Stack *stack, int *val)
{
if(stack == NULL)
return 0;
if(stack_is_empty(stack))
return 0;
stack->len--;
if(val)
*val = stack->stack[stack->len];
return 1;
}
int take(Stack *stack, int value)
{
if(stack == NULL)
return 0;
if(stack_push(stack, value) == 0)
fprintf(stderr, "stack is full, cannot push\n");
return stack->stack[stack->len / 2];
}
int main(void)
{
Stack stack;
stack_init(&stack);
printf("%d", take(5));
printf("%d", take(6));
printf("%d", take(7));
return 0;
}

How to debug this C code for a stack implementation?

I am new at C programming. I wrote some code for a stack exercise. The question is: one of the result is wrong, but when I debug step by step, the number changed abruptly. Could you help me solve this?
// #name mystack.c
// Created by lilei on 2017/3/10.
//
#include "mystack.h"
#include <malloc.h>
#include <stdio.h>
Stack createStack(){
Stack stack = (Stack)malloc(sizeof(Stack));
stack->top = -1;
return stack;
}
int isFull(Stack s){
if (s->top == MAXSIZE-1){
return 1;
} else{
return 0;
}
}
int push(Stack s, ElementType item){
if(!isFull(s)){
s->top++;
s->data[s->top] = item;
return 1;
} else{
printf("full!");
return 0;
}
}
int isEmpty (Stack s){
if(s->top == -1){
return 1;
} else{
return 0;
}
}
ElementType pop(Stack s){
if(!isEmpty(s)){
ElementType e = s->data[s->top];
s->top--;
return e;
}
}
void myPrintf(Stack s){
int len = s->top;
printf("The data are ");
while(len >= 0){
printf("%d ", s->data[len]);
len--;
}
printf("\n");
}
int main(){
Stack s = createStack();
for(int i = 0; i < 7; i++){
push(s, i*2);
}
myPrintf(s);
printf("isEmpty:%d, isFull:%d\n, pop one:%d", isEmpty(s), isFull(s), pop(s));
}
The result is
I can't see the declaration of Stack because you forgot to put it in th question, but it must be declared as a pointer to a struct e.g.
typedef struct
{
int top;
ElementType data[MAXSIZE];
} *Stack;
// ^- means pointer
So a Stack is a pointer type which means that, when you malloc it, you malloc only 4 or 8 bytes depending on whether you are compiling for 32 or 64 bit. The malloc line should be
Stack stack = malloc(sizeof *stack);
You were not allocating enough space on your stack for the actual stack structure which means that you are writing into bits of the heap you do not own and other things will write into the memory you think you have allocated for your stack.
There is another problem. What does your pop() function return if you try to pop something when the stack is empty? The answer is "could be anything". You either need to abort the program or return some error value.

C program waits forever on scanf

I have a C program that implements a stack.
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *link;
};
struct stack{
struct node *head;
struct node *data_node;
};
int push(struct stack *a_stack, int i){
a_stack->data_node = malloc(sizeof(struct node));
if(a_stack->data_node == NULL){
puts("Error: Cannot allocate sufficient memory.");
exit(1);
}
a_stack->data_node->data = i;
a_stack->data_node->link = a_stack->head;
a_stack->head= a_stack->data_node;
return 0;
}
int pop(struct stack *a_stack){
if(a_stack->head==NULL){
return '\n';
}
int temp = a_stack->head->data;
a_stack->data_node = a_stack->head;
a_stack->head = a_stack->head->link;
free(a_stack->data_node);
return temp;
}
int minimum(struct stack *a_stack){
if(a_stack->head==NULL){
return '\n';
}
int min = a_stack->head->data;
struct node *a_node = a_stack->head;
while(a_node!=NULL){
if(min>a_node->data){
min = a_node->data;
a_node = a_node->link;
}
}
return min;
}
int init_stack(struct stack *a_stack){
a_stack->head = NULL;
a_stack->data_node = NULL;
}
int handle_input(struct stack *test){
char* input_string = (char*)malloc(20);
scanf("%s", input_string);
// gets(input_string);
char* pop_cmd = "-";
char* min_cmd = "min";
int num;
if (strcmp(pop_cmd, input_string) == 0){
printf("%d\n", pop(test));
}
else{
if (input_string[0] == 'm'){
printf("%d\n", minimum(test));
}
else{
num = atoi(input_string);
push(test, num);
}
}
return 0;
}
int main(void){
int no_of_input, counter;
struct stack test;
init_stack(&test);
scanf("%d", &no_of_input);
for(counter=no_of_input; counter>0; counter=counter-1){
handle_input(&test);
};
return 0;
}
The problem is if I want to enter 'min' which is the command for calculating the minimum element of the array, the program waits forever on input. After searching around for quite a while I still have no idea why this is happening.
The scanf don't wait but you have infinite loop problem. In function minimum(), you only conditionally update a_node to next node in linked list:
int min = a_stack->head->data; //note
struct node *a_node = a_stack->head; //note
while(a_node!=NULL){
if(min > a_node->data){<-- "Always evaluates FALSE because: min is a_node->data"
min = a_node->data;
a_node = a_node->link; <--"Should NOT be here"
}
a_node = a_node->link; <--"but it should be here"
}
Also, if condition (min > a_node->data) is always evaluates false because of the reason:
min is a_stack->head->data and a_node is a_stack->head so min == a_node->date and min > a_node->data always evaluates false because you updated a_node in if body.
Additionally I figured out that you have memory leak in the function handle_input(). You should free() dynamically allocated memory explicitly. Read my suggestion below:
int handle_input(struct stack *test){
char* input_string = malloc(20); <-- "No need to type case"
// code here
free(input_string); <-- "Add this"
return 0;
}
Also, in:
int init_stack(struct stack *a_stack){
a_stack->head = NULL;
a_stack->data_node = NULL;
}
It should return void instead of int I think.
and min_cmd in handle_input() is unused.

Resources