Why I Always get RUNTIME ERROR?


  • 0
    K

    I don't know why i am given a runtime error with this code:

    typedef struct {
        int *values;
        int *mins;
        int maxSize;
        int size;
    } MinStack;
    
    void minStackCreate(MinStack *stack, int maxSize) {
        //stack = (MinStack *) malloc(sizeof(MinStack));
        stack->values = (int*) malloc(sizeof(int) * maxSize);
        stack->mins = (int*) malloc(sizeof(int) * maxSize);
        stack->maxSize = maxSize;
        stack->size = 0;
    }
    
    void minStackPush(MinStack *stack, int element) {
        if(stack->size >= stack->maxSize){
            return;
        }
        stack->values[stack->size] = element;
        if(stack->size > 0 && stack->mins[stack->size-1] < element){
            stack->mins[stack->size] = stack->mins[stack->size-1];
        }else{
            stack->mins[stack->size] = element;
        }
        stack->size ++;
    }
    
    void minStackPop(MinStack *stack) {
        if(stack->size <= 0){
            return;
        }
        stack->size--;
    }
    
    int minStackTop(MinStack *stack) {
        if(stack->size <= 0){
            return -1;
        }
        return stack->values[stack->size-1];
    }
    
    int minStackGetMin(MinStack *stack) {
        if(stack->size <= 0){
            return -1;
        }
        return stack->mins[stack->size-1];
    }
    
    void minStackDestroy(MinStack *stack) {
        free(stack->values);
        free(stack->mins);
        free(stack);
    }
    

    Is there someone can help me?


  • 3
    B

    I also have a runtime error with c language. My code runs ok in gcc and vs2013.

    This also happen in valid binary search tree.
    Now, I have to suspect the c compiler of leetcode has bugs.


  • 2
    Z

    The test codes in this problem are probably flawed. The method minStackCreate() does not construct any MinStack actually, it only initializes the parameter pointer stack. Suppose in the the main function we have

        MinStack *stack;
        minStackCreate(stack,0);
    

    This will probably not allocate valid memory to stack as the pointer is still nil. I suggest LeetCode modify the constructor prototype into something like MinStack *minStackCreate(int maxSize)
    Then the stack can be constructed outside the current file.


  • 0
    A

    Exactly. totally agree with you.


  • 0
    Z

    try remove free(stack) in minStackDestroy(stack)


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.