c++ - 为什么 IDEone 在获得输出后仍然显示运行时错误?

标签 c++ runtime-error

我的程序有什么问题? 它在我的 PC 上运行良好,但在 IDEone 中它提供了正确的输出,但显示运行时错误。请帮忙。

#include<bits/stdc++.h>

using namespace std;

struct student
{
    int vote;
};


int main()
{
  int t;
  cin>>t;

  while(t--)
  {
      int count=0;
      int n;
      cin>>n;
      vector <int> a(n);
      student s[n];
      int k;
      cin>>k;

      for(int i=1;i<=n;i++)
      {
           s[i].vote=0;
      }


      for(int i=1;i<=n;i++)
      {
           cin>>a[i];
      }
      int temp=0;

      for(int i=1;i<=n;i++)
      {
          if(a[i] != i)
          {
              temp=a[i];
              s[temp].vote++;
          }
      } 

      for(int i=1;i<=n;i++)
      {
          if(s[i].vote==k)
          {
              count++;
          }
      }

          printf("%d\n",count);

         }
return 0;
}

这是 IDEone 中显示的错误:-

Error in `./prog': free(): invalid next size (fast): 0x085cca10

最佳答案

  student s[n];

这声明了一个名为s 的数组。它包含 n 值。值是 s[0]s[n-1](如果愿意,您可以用手指数出它们,使用少量 n,比如5).

  for(int i=1;i<=n;i++)
  {
       s[i].vote=0;
  }

这尝试通过 s[n] 初始化值 s[1]。唯一的问题是 s[n] 不存在。数组中的最后一个值为 s[n-1]。此代码会破坏堆栈上的内存,从而导致未定义的行为。

同样的错误也发生在 a 数组上。

关于c++ - 为什么 IDEone 在获得输出后仍然显示运行时错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38676598/

相关文章:

c++ - 删除指向抽象类的指针 vector

c++ - for 循环上的 EXC_BAD_ACCESS(数组函数指针)

windows - 如何使用 MsgBox 在 VBS 中使用用户输入正确配置条件操作?

javascript - TypeScript运行时错误 'undefined'

java - 请澄清下面java代码中的问题

android - 使用 AppCompatActivity 而不是 Actionbar 时出现运行时错误

c++ - 使用 C++ WinAPI 在 Windows 10 上设置亮度

c++ - Boost 1.57 Boost.Context fcontext_t 资源管理

c++ - QCompleter,如何从数据库中获取 Id

android - 错误 : Could not access the Package Manager. 系统是否正在运行? - 在安卓工作室