tvishwa107
tvishwa107

Reputation: 311

(segfault) Error reading variable, cannot read variable at address X

I'm trying to write code for the gas station problem, where you have a fixed number of cities(linear) and you want to get from one end to the other with as few stops as possible, stopping wherever necessary to refill your gas tank. This is my main function; the function for calculation I've left out for now. I keep segfaulting saying unable to access tank and arr during the call to solver(the function I'm using to solve).

int main(void)
{
    int tank;
    int cities;
    int ans;

    scanf("%d %d",&cities, &tank);
    int *arr;

    arr=(int *)calloc(cities,sizeof(int));
    int *arr2;
    arr2=(int *)calloc(cities,sizeof(int));
    int i;

    for(i=0;i<cities;++i)
    scanf("%d",&arr[i]);
    arr2[i]=0;
    for(i=1;i<cities;++i)
    arr2[i]=arr[i]-arr[i-1];    
    for(i=0;i<cities;++i)
       printf(" %d ",arr2[i]);  


    ans=solver(tank, arr2,cities);
    printf("\n ans is %d",ans);

    return 0;

}

Can I get some pointers here(terrible pun)? I'm using the input as: 6 3 0 1 3 4 7 10

Arr holds [0,1,3,4,7,10] Arr2 holds the differences.

Upvotes: 2

Views: 6020

Answers (1)

Christophe
Christophe

Reputation: 73637

Your loop statement is the problem because of missing encolsing {}:

for(i=0;i<cities;++i)      // loop
    scanf("%d",&arr[i]);   // but there is no enclosing braces. so this is the only statement that loops
arr2[i]=0;              //<<<<<< this is executed when loop is finished, i.e i==cities 

In other words, you assign arr2[cities], which is out of bouds as it's indexed from 0 to cities-1. This causes the segfault.

Looking at the rest of the code, I guess you inteded to to:

...
for(i=0;i<cities;++i) {    // loop, but for the block 
    scanf("%d",&arr[i]);   
    arr2[i]=0; 
} 
...

Upvotes: 4

Related Questions