将void指针类型转换为int时出现分段错误

Segmentation fault on typecasting void pointer to int

本文关键字:分段 错误 int void 指针 类型转换      更新时间:2023-10-16

看到这个线程,我写了以下内容:如何将void*转换回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;
}

输出:

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

GCC-

我错过了什么?

好的,请忽略我之前的回答。请执行以下操作而不是(char*)port - (char*)0

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

您正在获取port:的地址

&port

将地址转换为int *:

(int *)(&port)

然后取消引用地址以返回您放入port:的整数值

*(int *)(&port)

忽略中间转换的潜在问题,从int开始,最后将其视为int*。换句话说,您将atoi()的结果视为地址,并尝试读取该地址的内存。

我根据这个SO答案进行了以下调整:

#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 = (char*)port - (char*)0;    
    cout << h;
}

结果:

$ g++ -Wall test.cpp
$ ./a.out 323
value: 
323
323

您尝试将port类型转换为int指针,但它不是指针。这是一种价值。您正在使用323作为指针。如果要获得int *,则键入argv[1]或指向port的指针。端口可能也不应该声明为void *,因为它在atoi()中被处理为int,它可能只是一个int

您正在取消引用一个指向您不拥有的内存的指针,这是未定义的行为

线下的更改

void* port = (void*) atoi (argv[1]); 

int port = atoi (argv[1]); 

使用此

int h=((int)端口);

因为您将int转换为void*

现在通过((int )port)void*转换回int

所以使用int h = ((int )port);