将void指针类型转换为int时出现分段错误
Segmentation fault on typecasting void pointer to int
看到这个线程,我写了以下内容:如何将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);
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?