运行时错误(SIGSEGV)
#include<iostream>
#include<string>
using namespace std;
int main()
{
char arr[1000][80];
char output[1000][80];
int n,i,j;
int num[1000];
cin>>n;
for(i=0;i<n;i++)
{
cin>>num[i];
cin>>arr[i];
}
for(i=0;i<n;i++)
{
for(j=(num[i]-1);j<(strlen(arr[i])-1);j++)
{
arr[i][j]=arr[i][j+1];
}
arr[i][j]='\0';
cout<<"\n"<<(i+1)<<" "<<arr[i];
}
return 0;
}
这是在 Spoj 上上传时出现上述错误的代码。相同的代码在 Borland C++ 上运行良好。
#include<iostream>
#include<string>
using namespace std;
int main()
{
char arr[1000][80];
char output[1000][80];
int n,i,j;
int num[1000];
cin>>n;
for(i=0;i<n;i++)
{
cin>>num[i];
cin>>arr[i];
}
for(i=0;i<n;i++)
{
for(j=(num[i]-1);j<(strlen(arr[i])-1);j++)
{
arr[i][j]=arr[i][j+1];
}
arr[i][j]='\0';
cout<<"\n"<<(i+1)<<" "<<arr[i];
}
return 0;
}
This is the code which while uploading on Spoj gives the above error. The same code runs fine on Borland C++.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据传递给该程序的输入,变量
n
可能超过 1000,cin>>arr[i]
可能读取超过 80 个字符,并且如果num[i] <= 0 || num[i] >= 80
那么您将索引超过字符串之一的开头或结尾。所有这些问题的存在都是因为此代码使用固定大小的数组并且不执行任何边界检查。Depending on the input you pass to this program, the variable
n
may be more than 1000,cin>>arr[i]
may read more than 80 characters, and ifnum[i] <= 0 || num[i] >= 80
then you will index past the beginning or end of one of your strings. All of these problems exist because this code uses fixed-size arrays and doesn't do any bounds checking.乍一看,没有什么本质上的错误。然而,当提供代码无法处理的输入时,段错误肯定是很有可能的。
例如,没有什么可以阻止在输入时写入
arr
的边界之外。是否有特定的输入导致此失败?
There's nothing inherently wrong as far as I can see at first glance. However a segfault is certainly very possible when providing inputs your code can't cope with.
There's nothing preventing from writing outside the boundaries of
arr
on input for example.Is there a specific input for which this fails?
变量
n
的值可以大于数组边界。这就是为什么您的代码可能会给出数组索引越界异常,进而给出运行时错误 (SIGSEGV
)。The value of the variable
n
can be greater than the array bounds. That is why your code can give an array index out of bounds exception, and consequently why it gives a runtime error (SIGSEGV
).