My code is the following:
#include <vector>
int main() {
std::vector<int> *vec;
vec->push_back(1);
return 0;
}
This program segfaults, no matter which compiler I try it with. I also tried using a smart pointer, but it also segfaults. I now have two questions:
- Why and how can I solve this?
- Does having a pointer to a
vector
(specifically a smart pointer) even make sense? In my online searches, I only saw it the other way around, avector
ofunique_ptr
's. Which makes more sense and why?
CodePudding user response:
Pointers are trivial objects, so the result of default-initializing one is that its value is indeterminant. Since that's what you did, your pointer doesn't point to anything. That means trying to access the thing it points to results in undefined behavior.
You need to create an object for your pointer to point to. For instance, you could dynamically-allocate a new std::vector<int>
:
std::vector<int>* vec = new std::vector<int>;
vec->push_back(1); // fine
delete vec; // dynamically-allocated, so you have to delete it when you're done with it
There's basically no reason to do that though. A std::vector
is already essentially just a pointer to a dynamically-allocated array plus a little bit of extra metadata to store the size of the array. There are very few legitimate reasons to dynamically-allocate a std::vector
instead of just declaring it locally (or as a data member of some class, etc):
std::vector<int> vec;
vec.push_back(1);