Re: void pointer cast segfaults



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

.



Relevant Pages

  • Re: confusion: casting function pointers
    ... pointer from the 'actual/other modules' that takes arguments of type ... list to types of void *). ... int main{ ... without a prototype, a number of special "promotion" rules take ...
    (comp.lang.c)
  • Re: invalid pointer adress
    ... >> pointer causes the program to exit with a core dump. ... struct s2{void *p;}; ... int leseExterneHinweise_masch_storno ... typedef struct s_AusdatFeldbeschreibung ...
    (comp.lang.c)
  • Should io(read|write)(8|16|32)_rep take (const|) volatile u(8|16|32) __iomem *addr?
    ... the destination pointer on user-space ... @src: ... const void *data, int bytelen); ...
    (Linux-Kernel)
  • Re: Ada Pointer Size Problem
    ... >> int. ... > pointer to an int. ... And you can't assign C pointer to integer without conversion; ... need not provide them if it doesn't have a suitable integer type. ...
    (comp.lang.ada)
  • Re: function pointer help!
    ... //the return void and input prameters are defined in the manual... ... void MyProjectView::CallHandler(int,unsigned int, unsigned int, void*) ... You are attempting to use a C++ member function as the callback, but the callback is defined in terms or C, not C++. ... The underlying problem is that C++ functions receive a hidden parameter, the 'this' pointer, so their signature is incompatible with C definitions. ...
    (microsoft.public.vc.mfc)