views:

148

answers:

7
+3  Q: 

Segmentation fault

I have come across a problem while writing a fairly simple program. I have a statically allocated vector as a global variable and in a function I'm trying to change the values of the elements and that is when the program stops and says segmentation fault. The code is something like this:

int a[10] = {0,0,0,0,0,0,0,0,0,0};

...

int bla(int i){
  ...

  a[i] = a[i] + i%3; //segmentation fault at this line

  ...
}

In the main function I have a "for" in which i takes values from 0 to 9.

Problem solved! Thank you :)

+7  A: 

What values of i are you passing in? if it is > 9 then you will get a segmentation fault.

You should debug it and step through checking the value of i when it is passed into the function. Also, your function should check any value of i passed in to make sure it is within range, as a general good practice,

Larry Watanabe
i is from 0 to 9
Renee
Maybe `bla` is called with some uninitialized `i`?
Heinzi
how do you know it is 0 to 9? Did you step through and see what value of i is when it crashes?
Larry Watanabe
+1 for stepping through and debugging
Corazu
+1  A: 

You're probably calling bla with an i >= 10 (or < 0) as the argument.

sepp2k
+2  A: 

Check to see what the values of i are. If they are ending up 10 or greater for whatever reason, that's the cause of the seg fault.

A good way to check would be to just call:

printf("i: %d\n", i);

At the top of blah.

Then go to where blah is called and figure out how i is ending up greater than or equal to 10. My guess would be you are calling it in a for loop and there is something wrong with the escape statement of the for loop (the middle one, the more technical term is escaping me at the moment). If you're calling it like this:

for(int i = 0; i < 11; i++)
    blah(i);

Or like this:

for(int i = 0; i <= 10; i++)
    blah(i);

Those are wrong and the cause of the segfault.

Daniel Bingham
printf is the cause of all segment faults. ;)
Filip Ekberg
+1  A: 

You might want to try a debugger, on linux try gdb. On windows, try Visual Studio or any other IDE with built in debugging. And track the error.

Filip Ekberg
A: 

You are probably modifying a read only vector.

Algorist
+4  A: 

Why didn't you write ?(Just a tip)

int a[10]={0}; //Similar to what you have written

However the main problem is because of the variable 'i'.What is the value of 'i' being passed to your function? If it is greater than 9 then that means you are trying to access the array out of bounds which invokes Undefined Behavior

Prasoon Saurav
A: 

I hope you made sure that you are only accessing existing elements, that is, i is in the range of 0..9 ? Couldn't think of anything else right now.

moritz