Getting Segmentation Fault error in C++ code - c++

#include<bits/stdc++.h>
using namespace std;
//FIRST REPEATING ELEMENT (APPROACH 2)
int main()
{
cout<<"running";
int n;
cin>>n;
int arr[n];
for(int i=1; i<=n; i++)
cin>>arr[i];
const int N = 1e5+2;
int idx[N];
for(int i=0;i<N;i++)
idx[i] = -1;
int minidx = INT_MAX;
for(int i=0;i<n;i++)
{
if(idx[arr[i]] != -1)
minidx = min(minidx, idx[arr[i]]);
else
idx[arr[i]] = i;
}
if(minidx == INT_MAX)
cout<<"-1"<<endl;
else
cout<<minidx + 1<<endl;
return 0;
}
I am writing this code for "First Repeating Element" question and trying to get the index of the first element that repeats.
On debugging, I am getting segmentation fault.
int main()
{ (in this line)
What does it mean and what can I do to remove this.

const int N = 1e5+2;
int idx[N];
That sounds like a big array to be allocated on the stack (400kb!). Try using malloc() to allocate an array of that size. Change that to something like
const int N = 1e5+2;
int* idx = (int*)malloc(N * sizeof(int));
You should also do the same for arr, particularly if you use large values for n.

The program has undefined behavior because you're going out of bound of the array. This is because in your for loop condition, you're using i<=n instead of i<n.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior. The program may just crash.
So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash.
So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.
Additionally, in Standard C++ the size of an array must be a compile time constant. This means that the following is incorrect in your program.
int n;
cin >> n;
int arr[n]; //not standard C++ since n is not a constant expression
1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.

Segmentation fault is due to usage of memory that you don't own, or in other words stack over flow. Most likely because you're creating an array of size 1e5+2 and looping over it, initializing every element. That's not the best way to find the recurrence of an element. Instead use a map with key value pairs.

Related

Hi, i have a problem with segmentation fault in c++

I'm working on a small sorting program with vector of pairs. But I'm getting a segmentation fault. I want to make a program that gets as input an vector of pairs containing files with there names and sizes, sorts the vector by the sizes of the files...
#include <iostream>
#include <vector>
#include <string>
using namespace std;
pair<string, int> min (vector<pair<string, int>> list){
pair<string, int> min;
for(int i = 0;i < list.size(); i++){
for(int j = 1; j < list.size(); i++){
if(list[i].second <= list[j].second)
min = list[i];
}
}
return min;
}
vector<pair<string, int>> sort (vector<pair<string, int>>& list){
vector<pair<string, int>> sorted;
for(int i = 0; i <= list.size(); i++){
sorted.push_back(min(list));
list.erase(list.begin()+(i-1));
}
return sorted;
}
int main(){
vector<pair<string, int>> files = {
{"f1", 30},
{"f2", 50},
{"f3", 25},
{"f4", 42},
{"f5", 10}
};
//min(files);
sort(files);
}
Problem 1
The problem is that after list.erase(list.begin()+(i-1)); the size of the vector has changed and so you need to recalculate the size and the indices used.
Problem 2
Additionally, for the inner loop involving j you're incrementing the outer loop variable i:
//------------------------------vvvv---->this should be j
for(int j = 1; j < list.size(); i++)
Problem 3
//-----------------------v------>what if i = 0? Undefined behavior
list.erase(list.begin()+(i-1));
In the above shown statement when i = 0 the expression list.erase(list.begin()+(0-1)) will lead to undefined behavior which is most probably the cause of seg fault you're observing.
Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior. The program may just crash.
So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash.
For example here the program doesn't crash but here it crashes.
So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.
Note
There may be additional logical problems in your code.
1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.

Vscode Complies the sorting algorithms but does not give any output. These are running fine in an online compiler.[I have MinGW installed]

/*Bubble sort*/
#include <iostream>
using namespace std;
//function to sort the array
int bubble_sort (int k[], int n){
int t,ct=1;
while(ct<n){
for(int i=0;i<n-ct;i++){
if(k[i]>=k[i+1]){
t=k[i];
k[i]=k[i+1];
k[i+1]=t;
}
ct++;
}
}
///loop to o/p the sorted array
for(int i=0;i<n;i++){
cout<<k[i]<<" ";
}cout<<endl;
return 0;
}
int main(){
int l;
int r[l];
cout<<"Enter the array size"<<endl;
cin>>l;
cout<<"Enter elements"<<endl;
for(int i=0;i<l;i++){
cin>>r[i];
}
bubble_sort(r,l);
return 0;
}
/*Insertion Sort*/
#include <iostream>
using namespace std;
//function to sort the array
int insertion_sort (int k[], int n){
int t,ct=1;
for(int i=1;i<n;i++){
int current=k[i];
int j=i-1;
while(k[j]>current && j>=0){
k[j+1]=k[j];
j--;
}
k[j+1]=current;
}
for(int i=0;i<n;i++){
cout<<k[i]<<" ";
}cout<<endl;
return 0;
}
int main(){
int l;
int r[l];
cout<<"Enter the array size"<<endl;
cin>>l;
cout<<"Enter elements"<<endl;
for(int i=0;i<l;i++){
cin>>r[i];
}
insertion_sort(r,l);
return 0;
}
The images attached show the output that I get in the terminal(which is blank) when I run the respective codes. The first algorithm illustrates the bubble sorting algorithm and the 2nd is meant to implement insertion sorting technique.
Any help in this regard is much appreciated!
Output in the terminal for bubble sort code
Output in the terminal for the insertion sort code
This part of your main contains typical C++ newbie errors.
int l;
int r[l];
cout<<"Enter the array size"<<endl;
cin>>l;
When you write int l, you only reserve some memory and give a nice name l to it. The value of l is arbitrary, or rubbish. Then you write int r[l]. This has several problems in it. First, the C++ language does not allow for such array definitions unless l is a constant whose value is known to the compiler. So this is an error, but many compilers do not flag it as an error, because they magically allow this particular departure from the standard and call it "extension" (VLA). The price for it is that your program is not standard and its behavior may be compiler-dependent. Second, as you already know, the value of l is undefined. Thus, any execution of your program may result in a different output, including correct (expected) behavior or even a sudden death (crash).
What yoo ned to do is this:
declare a variable that will store the array size. Give to it a meaningful name, like size, avoid names like l, as they are sometimes difficult to tell from 1 and I.
read its value from std::cin
construct an array of size size. Do not use the int a[size] syntax, for you already know it is not permitted by the standard. Use std::vector.
If after these changes your program still behaves in a strange way, call for help again.
Also, before you ask for help again, please include these flags to gcc:
-Wall -pedantic
They will issue lots of diagnostic information if your program does not adhere to usual coding standards (-Wall) or the C++ standard (-pedantic). Work on your source code until you can see no errors and no warnings.

Sample program crashes

I'm trying to make a program where the user inputs the "shape" by adding characters such as *,/ etc. and then print it on the screen the amount of times the user inputs. The program works fine but in the end it says program not responding. Any help with that?
#include <iostream>
using namespace std;
int main()
{
int a,h=1 ,b=0, x=7;
char test[a][100];
cout<<"Input how many lines ";
cin>>a;
cout<<"Input how many repeats ";
cin>>b;
for(int j=1; j<=a; j++)
{
cin>>test[j];
}
while(h<=b)
{
for(int c=1; c<=a; c++)
{
cout<<test[c]<<"\n";
}
h++;
}
return 0;
}
Your code invokes Undefined Behaviour (UB) here:
int a, ...;
char test[a][100];
You are trying to declare a fixed-size 2D array with an uninitialized variable (a).
Moreover, even if it was, variable-sized arrays are not standard C++.
If you enable the warning flags (such as Wall in GCC), you should get:
prog.cc:7:21: warning: 'a' is used uninitialized in this function [-Wuninitialized]
char test[a][100];
^
Moreover, array indexing starts from 0 and ends at the N - 1, where N is the size of the array. So you need to change this:
for(int j=1; j<=a; j++)
to this:
for(int j=0; j<a; j++)
in order to access the array right, and not out bounds as it happens when j gets the value of a. Accessing an array out of bounds causes Undefined Behaviour as well.

2D array elements not being read properly

The output is a string of numbers of entire row/column instead of a single number. Can someone please help me in this?
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int t;
cin>>t;
while(t--){
int n,m,cnt=0;
cin>>n>>m;
for(int i=0;i<=n+1;i++){
for(int j=0;j<=m+1;j++){
if(i==0||i==n+1||j==m+1||j==0) G[i][j]=0;
cin>>G[i][j];
}
}
cout<<G[1][2]<<endl;//this gives wrong o/p
return 0;
}
Most likely you are reading out of bounds due to a i <= n + 1 and j <= m + 1 conditions in your for loops thus invoking undefined behavior resulting in a corrupted stack which explains the output you are seeing. Modify the boundaries to:
i < n and j < m. Arrays are zero indexed in C++. First array element is accessed via somearray[0] and the last element is somearray[n-1] not somearray[n] which is what you are trying to access in your code. The same goes for multi-dimensional arrays. The statement of:
cout << G[i][j] << endl;
is wrongly placed outside the for loops. It should be inside the inner for loop. The array should be defined as a second statement in your while loop:
int G[n][m]; // Avoid VLAs
That being said variable length arrays are not part of the C++ standard and you should prefer std::vector and std::array to raw arrays.
Assuming G is a 2D array of size n x m, then you go out of bounds here:
for(int i=0;i<=n+1;i++) {
for(int j=0;j<=m+1;j++)
since array indexing starts from 0, and ends at size - 1.
As a result, your code invokes Undefined Behavior. To avoid that, simply change your double for loop to this:
for(int i = 0; i < n; i++) {
for(int j = 0;j < m; j++)

Error in program for modified bubble sort

Codeforces problem 339A-http://codeforces.com/problemset/problem/339/A
I have tried to sort the values stored at even places of the array(starting from 0).I get an error while running the program or program returns a junk value.What is wrong with my solution?
My solution:
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char s[101],temp;
int i,j;
cin>>s;
for(i=0;i<strlen(s);i+=2) //Bubble sorting values at even values of i.'+' is stored at odd values of i.
{
for(j=0;j<(strlen(s)-i-2);j+=2)
{
if(s[j]>s[j+2])
{
temp=s[j];
s[j]=s[j+2];
s[j+2]=temp;
}
}
}
cout<<s;
}
Your compiler should have warned you about the problem (you did switch on all warnings, yes? always do that!): Once i==strlen(s)-1, the loop for j is essentially unbounded, by the magic of arithmetic rules for signed/unsigned values.
for(unsigned j=0; j+2+i < strlen(s); j+=2)
does not have this problem. (i should be unsigned as well.)
Or stop the loop for i earlier. The problem in your code is still there then, but you won’t run into it. But I believe that is the worse route to take – fix the bug, and then optimize by observing i doesn’t need to go as far up, because the last character already forms a sorted sequence.
For odd lengths len of s, the outer loop runs until i==len-1. The inner loop then terminates at len - len - 1 - 2. Since strlen returns an unsigned type, this evaluates to a very large unsigned number, causing the inner loop to read way beyond the end of s. Eventually you'll reach memory you don't have access to read or write, causing the crash.
You can fix this by ending the outer loop sooner
int len = strlen(s);
for(i=0;i<len-2;i+=2) {
for(j=0;j<(len-i-2);j+=2)
Change this:
for(i=0;i<strlen(s);i+=2)
Into this:
for(i=0;i<strlen(s) - 2;i+=2)
Otherwise the s value be handled beyond its end-point
here is my code
void bubble(int a[], int n){
for(int i=0; i<n; i++){
int swaps=0;
for(int j=0; j<n-i-1; j++){
if(a[j]>a[j+1]){
int t=a[j];
a[j]=a[j+1];
a[j+1]=t;
swaps++;
}
}
if(swaps==0)
break;
}
}