Reputation: 624
Well, I have searched all over and couldn't find anything, so please excuse if this question was already asked.
In C (gcc, Linux x86_64), trying to test a pointer using this code works:
if(ptr) { ... }
But I get a segfault when I do this:
while(set1) {
n++;
set3 = realloc(set3, sizeof(int) * n);
set3[n-1] = *set1;
}
or even this:
for(; set1; set1++) {
n++;
set3 = realloc(set3, sizeof(int) * n);
set3[n-1] = *set1;
set1++;
}
Can someone explain me this? Where am I going wrong? :S
NB: The code inside `if' said above was just for testing, I don't need it actually
Upvotes: 2
Views: 111
Reputation: 477680
I think you are misunderstanding what "testing a pointer" means. The condition if(p)
is identical to if(p != 0)
, so all you are testing is whether the pointer is null or not. There is nothing that tells you whether it's OK to dereference any given pointer.
In particular, for(; ptr; ptr++) { ... }
will just continue incrementing the pointer forever; if you dereference ptr
in the body, you will almost certainly cause an access violation eventually.
You are responsible yourself for knowing by how much you can increment the pointer!
(Silly aside: If you are not dereferencing ptr
at all, this might loop around until ptr
overflows and is 0 again, but this may never happen depending on the initial value of ptr
and on sizeof(*ptr)
.)
Upvotes: 4
Reputation: 7180
i'd guess ptr is not null (so the if will evaluate to true) but your pointer is not valid (i.e: it was freed, or even if ptr=1 the "if" will evaluate to true but you wont be able to access the memory position 1)
maybe you can try fprintf(stdout, "%p", ptr) in different parts of your code so you can trace where the value was messed up, we really need more details here :)
Upvotes: 1