0

Touching C after a long time. I am getting a run time error in the following code. The IDE[C-Free] which I am using is not showing the exact error but it shows 'StackMin.exe' has stopped working.

Here, I am using two structures, struct stack is for stack and struct AdvanedStack is for storing two stacks. In the end I want to print the capacity of both the stacks which are in the AdvancedStack

Code is :

#include<stdio.h>

struct stack {
    int capacity;
    int top;
    int *array;
  };

struct AdvancedStack{

    struct stack* elementStack;
    struct stack* minStack; 

};


struct stack* createStack()
{
    struct stack* myStack= (struct stack*)malloc(sizeof(struct stack));
    myStack->capacity=5;
    myStack->top=-1;
    myStack->array= malloc(myStack->capacity * sizeof(int));

    return myStack;

}

struct AdvancedStack* createAdvancedStack()
{
  struct AdvancedStack *myStack = (struct AdvancedStack*)malloc(sizeof(struct AdvancedStack));
    myStack->elementStack=createStack();
    myStack->minStack=createStack();
}

int main()
{
    struct AdvancedStack* advStack = createAdvancedStack();

   printf("%d",advStack->elementStack->capacity);
    printf("%d",advStack->minStack->capacity);
}
Vikas Mangal
  • 821
  • 3
  • 10
  • 23

1 Answers1

3

You forgot to return myStack from the createAdvancedStack() function.

struct AdvancedStack* createAdvancedStack()
{
    struct AdvancedStack *myStack = malloc(sizeof(struct AdvancedStack)); //Don't cast the result of malloc

    myStack->elementStack=createStack();
    myStack->minStack=createStack();

    return myStack; //You forgot this
}

Read this to know why you should not cast the result of malloc.

Community
  • 1
  • 1
Spikatrix
  • 20,225
  • 7
  • 37
  • 83