使用指针管理vector无法push_back

本文解析了C++中遇到Segmentation Fault的原因,重点在于指针问题,如未初始化、越界或内存释放后的使用。通过实例展示了如何避免该错误,如使用`make_shared`正确初始化vector。
摘要由CSDN通过智能技术生成

今天犯了一个比较蠢的错误

#include <vector>
#include <memory>

using std::vector;
using std::shared_ptr;

int main()
{
    shared_ptr<vector<int>> sp;
    sp->push_back(1);
	return 0;
}

给我报了一个Segmentation fault,什么是seg fault呢?

A segmentation fault occurs when your program attempts to access an area of memory that it is not allowed to access. In other words, when your program tries to access memory that is beyond the limits that the operating system allocated for your program.

Seg faults are mostly caused by pointers that are −

  • Used to being properly initialized. (估计写错了,应该是没有正确初始化或者是没有初始化)
  • Used after the memory they point to has been reallocated or freed.
  • Used in an indexed array where the index is outside of the array bounds.

—— What is a segmentation fault in C/C++?

简言之,就是访问了不该访问的内存,通常关联的代码用到指针,要么指针是野指针、空悬指针,要么下标越界了。

在我的程序里面,我只定义了一个sp,但是这个sp究竟指向谁,我没有说明。那么 push_back 的时候,1 这个元素应该放到哪段内存中呢?自然就报了seg fault。

#include <vector>
#include <memory>

using std::vector;
using std::shared_ptr;

int main()
{
    shared_ptr<vector<int>> sp(make_shared<vector<int>>());
    sp->push_back(1);
	return 0;
}

修改方法:用 make_shared<vector<int>>() 去开辟一段内存,() 里面没参数,所以对 vector 值初始化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值