Dereferencing a pointer in a ‘for’ loop initializer creates a segmentation fault

Take a close look here:

for (int i=3, (*p)=0 ; i>=0; i--)

In the first part of the for you’re defining a new pointer variable named p which shadows the p defined earlier and initializing it to NULL. You then dereference the NULL pointer in the loop which causes the segfault.

You can’t have both a variable definition and an assignment to an existing variable together like that, so move the assignment of *p to before the loop:

*p = 0;
for (int i=3; i>=0; i--)

Or you can define i outside of the loop:

int i;
for (i=3, (*p)=0 ; i>=0; i--)

You could squeeze these together by abusing the comma operator:

for (int i=(*p=0,3) ; i>=0; i--)

Here the assignment to p happens as part of the initializer for i so it doesn’t declare a new variable. But I wouldn’t recommend this as it would make your code more difficult to read and understand.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)