带有和不带有初始化的 std::vector 分段错误 [英] std::vector segmentation fault with and without initialization

查看:32
本文介绍了带有和不带有初始化的 std::vector 分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 C++ 中的向量做一些实验.我使用的代码如下

I was doing some experimentation with vectors in C++. The code I'm using is the following

#include <vector>
#include <iostream>

int main()
{
   std::vector<float> aVector = std::vector<float>(10);  // IMPORTANT LINE
   std::cout << "Vector size: " << aVector.size() << std::endl;
   aVector.clear();
   aVector[0] = 2.2;
   std::cout << "Vector size: " << aVector.size() << std::endl;
   aVector.push_back(0.1);
   std::cout << "Vector size: " << aVector.size() << std::endl;
   aVector.clear();
   std::cout << "Vector size: " << aVector.size() << std::endl;
   aVector[0] = 2.1;
   std::cout << "Vector size: " << aVector.size() << std::endl;

   return 0;
}

如果我有向量,用 N 个元素初始化它,然后清除向量并尝试赋值 aVector[0] = 1.1 程序一直运行到最后,没有分段错误.

If I have the vector, initialize it with N elements and then clear the vector and try to put assign value aVector[0] = 1.1 the program goes all the way to the end with no segmentation faults.

另一方面,如果我创建了一个向量但没有传递初始元素的数量,当尝试使用 aVector[0] = 1.1 分配值时,它会导致程序崩溃.

On the other hand if I create a vector but don't pass the number of initial elements, when trying to assign the value with aVector[0] = 1.1 it will crash the program.

出现分段错误的唯一方法是因为我试图写入无效的内存地址.因此,根据我的理解,创建向量而不是初始化意味着指向实际向量数据的指针在初始化向量和清除时无处指向任何地方,但会保留指向已分配内存的指针,但向量的大小仅缩小到 0?这是否意味着即使在清除向量后,先前存储的值仍然存在?

The only way a segmentation fault can arise is because I'm trying to write to an invalid memory address. So, to my understanding, creating the vector and not initializing means that the pointer to the actual vector data points to nowhere while initializing the vector and clearing keeps a pointer to an allocated memory but the size of the vector only shrinks to 0? does it mean that even after clearing a vector the values previously stored are still there?

这是规范中定义的行为吗?我原以为 clear 会擦除并释放先前分配的内存.

Is this the behavior defined in the specification? I would've expected that clear erases and frees the memory previously allocated.

推荐答案

截至 doc, clear() 使 std::vector 对象的任何元素的所有内容(引用、指针...)无效,但不会释放内存因为 capacity() 保持不变.

As of the doc, clear() invalidates everything (references, pointers...) to any element of the std::vector object, but does not deallocates memory since capacity() remains unchanged.

这篇关于带有和不带有初始化的 std::vector 分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆