Baba_yaga
Baba_yaga

Reputation: 3

what is segmentation fault

Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array.

Example

My code is:

#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    int n,b;
    scanf("%d",&n);
    scanf("%d",&b);
    int arr[3][b];
    for(int i=0;i<b;i++)
    {
        for(int j=0;j<3;j++)
        {
            scanf("%d",&arr[i][j]);
        }
    }
    int man[n];
    for(int i=0;i<n;i++)
    man[i]=0;
    int start,end,change;
    for(int i=0;i<b;i++)
    {
        start=arr[i][0]-1;
        end=arr[i][1]-1;
        change=arr[i][2];
        for(int j=start;j<=end;j++)
        {
            man[j]=man[j]+change;
            //printf("%d",change);
        }
    }
    for(int i=0;i<n-1;i++)
    for(int j=0;j<n-i-1;j++)
    if(man[j]<man[j+1])
    {
        int temp=man[j+1];
        man[j+1]=man[j];
        man[j]=temp;
    }
    printf("%d",man[0]);
}

One of the input was

40 30
29 40 787
9 26 219
21 31 214
8 22 719
15 23 102
11 24 83
14 22 321
5 22 300
11 30 832
5 25 29
16 24 577
3 10 905
15 22 335
29 35 254
9 20 20
33 34 351
30 38 564
11 31 969
3 32 11
29 35 267
4 24 531
1 38 892
12 18 825
25 32 99
3 39 107
12 37 131
3 26 640
8 39 483
8 11 194
12 37 502

When the value of n and b is low my code gets executed but when the values are higher it shows segmentation fault.

Can anyone help me?

Upvotes: 0

Views: 79

Answers (2)

thomi
thomi

Reputation: 1687

A segmentation fault - in your case at least - happens if you are trying to access memory that you did not allocate properly. E.g. your arr has a length of 3 integers in its first dimension. So if you enter b and it is bigger than 2, the nested loop will fail at the point you get to scanf("%d", &arr[something bigger than or equal to 3][j]). Probably you need to switch the loops around? Or the array dimensions?

Upvotes: 0

chux
chux

Reputation: 153456

At least this problem: Wrong array dimensions.

// int arr[3][b];
int arr[b][3];

for(int i=0;i<b;i++) {
    for(int j=0;j<3;j++) {
        scanf("%d",&arr[i][j]);
    }
}

Upvotes: 1

Related Questions