Reputation: 2977
#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++.
Upvotes: 0
Views: 3955
Reputation: 671
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
).
Upvotes: 0
Reputation: 24328
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 if num[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.
Upvotes: 2
Reputation: 17705
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?
Upvotes: 0