Re: void pointer cast segfaults
- From: "Peter Nilsson" <airia@xxxxxxxxxxx>
- Date: 4 May 2005 20:55:07 -0700
Andreas Schmidt wrote:
> I am trying to understand the behavior of void pointers.
You're really trying to explain why accessing random addresses
causes your machine to segfault.
> Can someone explain to me why I get a segfault for the
> following program?
>
> #include <stdio.h>
>
> void* plusone(void* i){
> int* arg = (int*)i;
The (int *) cast is unnecessary. But the conversion may fail if the
resulting pointer is not suitably aligned for an int.
> int result = (*arg + 1);
You're trying to get an int value from memory you probably don't own.
> return (void*)result;
The conversion of an int to a void * is implementation defined.
> }
> int main(){
> void* w1 = (void*)10;
Again the conversion is implementation defined. It is utterly useless
in portable programming because you have _no idea_ what 10 will
represent when converted to a pointer.
> void* result = plusone(w1);
> printf("%d", *(int*)result);
Again you try and grab an int value from memory you don't own.
Also, without a trailing \n, you have no guarantee of output anyway.
> }
>
> According to gdb, the cast in the first line of plusone gives
> the segfault.
> Why??
What are you actually trying to do? If it is implementation specific,
then ask in an implementation specific newsgroup.
If you're just trying things, then realise that C is probably the
_worst_ language to learn through pure experimentation.
--
Peter
.
- Follow-Ups:
- Re: void pointer cast segfaults
- From: Andreas Schmidt
- Re: void pointer cast segfaults
- References:
- void pointer cast segfaults
- From: Andreas Schmidt
- void pointer cast segfaults
- Prev by Date: void pointer cast segfaults
- Next by Date: Re: make compilation fail
- Previous by thread: void pointer cast segfaults
- Next by thread: Re: void pointer cast segfaults
- Index(es):
Relevant Pages
|