运行时检查失败#2 - 变量's'周围的堆栈已损坏

时间:2013-06-03 07:28:10

标签: c++ pointers visual-studio-2012 stack runtime-error

我遇到了这个问题:运行时检查失败#2 - 在Visual Studio 12中,变量's'周围的堆栈已损坏。我也在codeblock中尝试这个但面临同样的问题。我也在ideone.com中运行我的代码,它显示运行时错误。帮帮我 ? 我的代码是:

#include<iostream>
  #include<stdio.h>
  #define MAX 50
  using namespace std;
  typedef struct
  {
    long var[20];
    long pos;
  }stack;

   void init_stack(stack *st)
   {
       long i;
       for(i=0; i<MAX; i++)
        st->var[i] = -1;
       st->pos = 0;
     return ;
  }

  void push(stack *st, long item)
  {
    if(st->pos == MAX)
    {
        printf("stack overflow \n");
    }
    else
    st->var[st->pos+1] = item;
    st->pos++;
    return ;
  }

  void pop(stack *st)
  {
    //if(empty(st))
    if(st->pos == 0) 
        printf("stack underflow \n");
    else
    st->var[st->pos] = -1;
    st->pos--;
    return ;
  }

  long top(stack *st)
  {
    long temp;
    temp = st->var[st->pos];

    return temp;
    }

bool empty(stack *st)
{
    if(st->pos==0)
        return true;
    else
        return false;
}

int main()
{
    stack s;
    long i, n=9, t;
    init_stack(&s);
    printf("STACK PUSH\n");
    for(i=1; i<=n; i++)
    {
        push(&s, i);
        t = top(&s);
        printf("  %ld\n", t);
    }
    printf("STACK POP\n");
    for(i=1; i<=n; i++)
    {
        t = top(&s);
        printf("  %ld\n", t);
        pop(&s);
    }
    return 0;
}

#include<iostream> #include<stdio.h> #define MAX 50 using namespace std; typedef struct { long var[20]; long pos; }stack; void init_stack(stack *st) { long i; for(i=0; i<MAX; i++) st->var[i] = -1; st->pos = 0; return ; } void push(stack *st, long item) { if(st->pos == MAX) { printf("stack overflow \n"); } else st->var[st->pos+1] = item; st->pos++; return ; } void pop(stack *st) { //if(empty(st)) if(st->pos == 0) printf("stack underflow \n"); else st->var[st->pos] = -1; st->pos--; return ; } long top(stack *st) { long temp; temp = st->var[st->pos]; return temp; } bool empty(stack *st) { if(st->pos==0) return true; else return false; } int main() { stack s; long i, n=9, t; init_stack(&s); printf("STACK PUSH\n"); for(i=1; i<=n; i++) { push(&s, i); t = top(&s); printf(" %ld\n", t); } printf("STACK POP\n"); for(i=1; i<=n; i++) { t = top(&s); printf(" %ld\n", t); pop(&s); } return 0; }

1 个答案:

答案 0 :(得分:1)

您将var声明为持有20个元素,但是对其进行了MAX次迭代,MAX被定义为50。这可能不是你想要做的。试试:

long var[MAX];