Segmentation fault when updating an array value
I have come across a problem while writing a fairly simple program. I have a statically allocate开发者_如何学God 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.
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,
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.
You're probably calling bla with an i >= 10
(or < 0) as the argument.
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.
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
You are probably modifying a read only vector.
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.
精彩评论