Dereferencing a pointer in a 'for' loop initializer creates a segmentation fault
I'm having a problem using pointers in a for
loop. In my for
loop initializer, I dereference an int
pointer and give it a value of '0'. When I use that dereferenced pointer in the loop I get a segmentation fault, and I don't understand why. I am using Code::Blocks and the C GNU GCC compiler.
Looking at the watch window I can see that during the
for
loop the variable has a random number.It seems that the dereferenced pointer loses scope during the
for
loop.
The code:
#include <stdio.h>
int main(void)
{
int val = 0;
int *p = NULL;
int answer = 0;
p = &val;
*p = 1; // This dereferences and sets to one successfully
for (int i=3, (*p)=0 ; i>=0; i--) // Here *p is a random number
{
printf("do stuff");
(*p) += 1; // Here it causes a segmentation fault
}
answer = *p;
}
I thought that there would be no problems using a pointer the way I am.
Solution 1:
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.
Solution 2:
You are declaring a completely new variable called p
:
for (int i=3, (*p)=0 ; i>=0; i--)
This is the same as:
for (int i=3, *p=0 ; i>=0; i--)
So you are creating an int i
and an int *p
, which points to address 0. This is not the same p
as the one defined previously. It just shadows it. So when you dereference it, you get the segfault.
Solution 3:
Tip: Use -Wshadow
to get a warning when a variable shadows another one.
[] $ gcc main.c -Wshadow
main.c: In function ‘main’:
main.c:13:21: warning: declaration of ‘p’ shadows a previous local [-Wshadow]
13 | for (int i=3, (*p)=0 ; i>=0; i--) // Here *p is a random number
| ^
main.c:6:10: note: shadowed declaration is here
6 | int *p = NULL;
| ^
https://coliru.stacked-crooked.com/a/5de37f53cf0b094d