Take the 2-minute tour ×

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.

share|improve this question
the obvious answer is your index i is invalid. Can you post some more code which shows how i is being calculated? –  Naveen Jan 4 '10 at 14:13
So what was the solution? –  Constantin Jan 4 '10 at 16:17

7 Answers 7

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,

share|improve this answer
i is from 0 to 9 –  Renee Jan 4 '10 at 14:13
Maybe bla is called with some uninitialized i? –  Heinzi Jan 4 '10 at 14:14
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 Jan 4 '10 at 14:15
+1 for stepping through and debugging –  Corazu Jan 4 '10 at 14:20

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:


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:


Or like this:


Those are wrong and the cause of the segfault.

share|improve this answer
printf is the cause of all segment faults. ;) –  Filip Ekberg Jan 4 '10 at 17:20

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

share|improve this answer

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.

share|improve this answer

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

share|improve this answer

You are probably modifying a read only vector.

share|improve this answer

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.

share|improve this answer

Your Answer


