Home > Blockchain >  Why is this code giving me segmentation fault?
Why is this code giving me segmentation fault?

Time:01-29

I have written a code for the rainwater trapping problem https://www.geeksforgeeks.org/trapping-rain-water/ , but am getting segmentation fault in this code.

I have passed the given array into the two methods and as far as I have checked, am not trying to access any invalid memory.

#include<bits/stdc  .h>
using namespace std;

vector<int> maxl(int arr[],int n){
    vector<int> v1;
    v1[0]=arr[0];
    for(int i=1;i<n;i  ){
        v1[i]=max(v1[i-1],arr[i]);
    }
    return v1;
}
 
vector<int> maxr(int arr[],int n){
    vector<int> v2;
    v2[n-1]=arr[n-1];
    for(int i=n-2;i>=0;i--){
        v2[i]=max(v2[i 1],arr[i]);
    }
    return v2;
}

int main(){
    int a[]={3,0,0,2,0,4};
    vector<int> vl,vr;
    vl=maxl(a,6);
    vr=maxr(a,6);

    int lvl[6], unit[6];
    int s=0;
    for(int i=0;i<6;i  ){
        lvl[i]=min(vl[i],vr[i]);
        cout<<lvl[i]<<" ";
        unit[i]=lvl[i]-a[i];
        s =unit[i];
    }
    cout<<s;
    return 0;
}

Please lemme know my mistake :) Thanks

CodePudding user response:

Your code tries to access objects that don't exist. For example:

vector<int> maxl(int arr[],int n){
    vector<int> v1; // v1 is an empty vector
    v1[0]=arr[0]; // you try to modify the first element

An empty vector has no first element, so you can't modify its first element.

CodePudding user response:

Use gdb to check what is happening.

Starting program: /home/user/a.out 

Breakpoint 1, main () at test.cpp:22
22  int main(){
(gdb) n
23      int a[]={3,0,0,2,0,4};
(gdb) 
24      vector<int> vl,vr;
(gdb) 
25      vl=maxl(a,6);
(gdb) s
maxl (arr=0x0, n=21845) at test.cpp:4
4   vector<int> maxl(int arr[],int n){
(gdb) n
5       vector<int> v1;
(gdb) 
6       v1[0]=arr[0];
(gdb) 

Program received signal SIGSEGV, Segmentation fault.
maxl (arr=0x7fffffffdd80, n=6) at test.cpp:6
6       v1[0]=arr[0];

You can see the problem is in assigning v1[0]=arr[0].

  •  Tags:  
  • Related