0

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;
}
trincot
  • 317,000
  • 35
  • 244
  • 286
  • 1
    You shouldn't use `struct stack * sp = (struct stack *) malloc(sizeof(struct stack));` in any cases. [c - Do I cast the result of malloc? - Stack Overflow](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – MikeCAT Jun 16 '21 at 19:15
  • `struct stack *ptr;` just declares a pointer. You have to assign a valid pointer later if you want to dereference `ptr`. – MikeCAT Jun 16 '21 at 19:19
  • Your program has high chance to be terminated due to Segmentation Fault for trying to write (or read) to invalid place when you dereference an uninitialized pointer. Such invalid dereference occurs in your program before trying to print anything. – MikeCAT Jun 16 '21 at 19:23
  • when i didn't allocate memory to struct stack *sp in heap the code is not giving output but when i allocate memory to it start giving correct output. Like in this function i don't allocate memory to struct stack *sp but it is working. `int parenthesisbalance(char *exp) {struct stack *sp;sp->size = 100;sp->top = -1; sp->arr(char*)malloc(sp>size*sizeof(char)); for (int i = 0; exp[i]!= '\0'; i++) {if (exp[i]=='('){push(sp,'(');} else if (exp[i]==')') {if (isempty(sp)){return 0;} else{pop(sp);}}} if (isempty(sp)){return 1;}else{return 0;}}` – Abhinav 1036 Jun 16 '21 at 19:34
  • *Undefined behavior* is invoked when uninitialized pointer is dereferenced. It can result in anything and need not crash. – MikeCAT Jun 16 '21 at 19:36
  • When you have a pointer that doesn't point anywhere yet, but you use it, and your program seems to work, that's textbook undefined behavior. See [this question](https://stackoverflow.com/questions/37087286/c-program-crashes-when-adding-an-extra-int). – Steve Summit Jun 16 '21 at 19:43

1 Answers1

1

Two things to always remember when working with pointers in C:

  1. Memory allocation is your problem. You have to think about the allocation of the memory which a pointer variable points to.
  2. 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.

  1. The compiler allocates space to store one pointer. This pointer is known as sp. But:
  2. 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.

Steve Summit
  • 45,437
  • 7
  • 70
  • 103