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);
}

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Adding the return statement worked. Thanks for that. But is there any specific reason why to avoid casting the result of malloc here. Does it make any difference?
Also, main should return a value or call exit().
Read the link, there are several reasons.
@VikasMangal , Read the link in my answer to know the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.