How can this be causing a segfault?

Sep 23, 2009 at 8:12am
I've been searching for the source of a segmentation fault for a long time, and I eventually narrowed it down to a single for loop. I couldn't figure out what in the loop was causing the error, so I started stripping it down more and more until I was left with this:

1
2
int y = 0;
for (int x;x<y;x++) {}


I have tested it many times, and I'm sure the for loop is what's causing the fault. If I take it out, the function works perfectly. If I have it in, it segfaults.

This looks just like an ordinary for loop to me. It's not calling any functions or accessing any data through pointers. What could possibly be the problem?
Sep 23, 2009 at 8:27am
closed account (z05DSL3A)
1
2
int y = 0;
for (int x;x<y;x++) {}

x in not initialised.
Sep 23, 2009 at 3:23pm
Then it should default to zero, right? Besides, even if I do
1
2
int y = 0;
for (int x=0;x<y;x++) {}

It still segfaults.
Sep 23, 2009 at 3:35pm
closed account (z05DSL3A)
You are probably going to have to post the surrounding code...
Sep 23, 2009 at 4:21pm

Then it should default to zero, right? Besides, even if I do
1
2
int y = 0;
for (int x=0;x<y;x++) {}

It still segfaults.


I don't think for loop is creating any problem, because if x = 0 and y =0 then x can never be less than 0. So it will technically, not even go into the for loop.

As GreyWolf said, post the surrounding code.

EDIT: typo
Last edited on Sep 23, 2009 at 4:21pm
Sep 23, 2009 at 4:28pm
Could be one of those cascading errors. Something else is causing the error in the code, but for whatever reason without the for-loop it doesn't have the issue.

Or it might be the compiler doing optimizations. That can cause issues.
Sep 24, 2009 at 6:56am
Well, thanks everyone who responded. I just went and moved the loop into its own function. I still don't know what went wrong, but I least it works.

Just so I know in the future, how much surrounding code would I have needed to post? The program is pretty large, and the function is also pretty big, and wouldn't make sense out of context. I don't see how anything in either of them could have effected this for loop though.

Thanks again for responding.
Topic archived. No new replies allowed.