Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault on typecasting void pointer to int

Seeing this thread I wrote the following: How do I convert from void * back to int

#include <iostream>
#include <stdlib.h>
using namespace std;

int main (int argc, char *argv[])
{
    void* port = (void*) atoi (argv[1]);

    cout << "\nvalue: \n" << atoi (argv[1]) << "\n";

    int h = *((int *)port);
    cout << h;
}

output:

anisha@linux-dopx:~/> ./a.out 323

value: 
323
Segmentation fault
anisha@linux-dopx:~/>

GCC

What's the point that I am missing?

like image 959
Aquarius_Girl Avatar asked Feb 28 '26 17:02

Aquarius_Girl


2 Answers

Okay, please ignore my previous answer. Instead of (char*)port - (char*)0, please do the following:

int h = *(int *)(&port);

You're getting the address of port:

&port

Casting the address to an int *:

(int *)(&port)

Then dereferencing the address to get back the integer value you put into port:

*(int *)(&port)
like image 198
Alex Reynolds Avatar answered Mar 03 '26 08:03

Alex Reynolds


Ignoring potential issues with the intermediate conversions, you start with an int and end up treating it as if it were int*. In other words, you treat the result of atoi() as an address, and try to read the memory at that address.

like image 37
NPE Avatar answered Mar 03 '26 07:03

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!