Andreas said:
Can someone explain to me why I get a segfault for the
following program?
According to gdb, the cast in the first line of plusone
gives the segfault. Why??
#include <stdio.h>
int main(){
void* w1 = (void*)10;
In general, this is illegal: you cannot cast an int to a pointer.
In your case, you will probably end up with a pointer to address
number 10 on your PC.
void* result = plusone(w1);
Now let's look at plusone() (I have rearranged your post a little):
void* plusone(void* i){
int* arg = (int*)i;
You are casting the address 10 to be a pointer to int. This
may also be illegal (for example, on some systems, ints can
only reside at addresses that are a multiple of 4).
This is definitely a problem: you are retrieving an int from
address 10. On a system like Windows XP or Unix or Linux,
you will get a segmentation fault because your program
is not allowed to access address 10 (it can only access
addresses in its own address space).
Casting an int to a pointer -- illegal, as I mentioned before.
Now we're back to main():
printf("%d", *(int*)result);
Again, dereferencing a pointer to an address you probably
don't own, this will probably give you a segmentation fault.
}
I am trying to understand the behavior of void pointers.
Your code really has nothing to do with void pointers as such,
you could have used int pointers or char pointers and
got the same problems. Generally, you cannot convert between
ints and pointers in this way.
A "void pointer" (or more accurately, a pointer-to-void) is
a pointer where you don't know the type of what it's pointing
to. You can convert other POINTERS into void pointers, and
convert them back again. You can't convert ints etc. into
void pointers.
Here's an example of what you can do:
void plusone(void *ptr)
{
*(int *)ptr += 1;
}
int main()
{
int x = 5;
void *ptr = &x;
plusone(ptr);
printf("%d\n", x);
}