代码的分段错误
segmentation fault for the code
#include<iostream>
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
using namespace std;
union type{
int a;
char b;
int *p;
char *s;
int arr[10];
};
int fn(union type *exp){
exp->p = exp->p+1;
cout << *(exp->p);
cout << "n";
return 0;
}
int main(){
union type *str;
str->a = 10;
str->b = 'n';
str->p = &(str->a);
cout << (str->p);
cout << "n";
fn(str);
cout << str->p;
cout << "n";
return 0;
}
这段代码给了我分段错误。是因为我需要使用 malloc 显式地将内存分配给联合吗?我是编码新手,并尝试学习c ++。
这段代码给了我分段错误。是因为我需要 使用 malloc 显式将内存分配给联合??
右。您的str
指针没有指向有效的内存位置,甚至没有初始化。因此,在编写str->a
之前,您需要将str
设置为某些内容。
您正在声明指向联合的指针,但指针未指向任何有效内存,您需要 malloc/new 来获取该内存。 它指向的是未定义的(垃圾指针)。
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 为什么我使用 std::copy() 收到运行时错误(分段错误)?
- 为什么我的代码包含错误分段错误(核心转储)?
- 为什么会出现此错误?- 分段错误(核心转储)
- 意外的运行时错误(分段错误)
- C++将文本文件读入数组,运行错误:分段错误
- mmap 错误:分段错误/指针无效错误
- 在我的代码中找不到错误....分段错误
- 错误:分段故障(核心转储)阵列
- 用string.h将错误分段到队列中
- c++字符串流转换错误:分段错误
- 为什么我的代码显示错误分段错误(核心转储)