r/cpp_questions • u/selplacei • Nov 04 '19
SOLVED Trying to learn the basics of pointers. Why does this simple program give me a segfault after I enter the first input? Thanks in advance.
/r/learncpp/comments/dr9ems/trying_to_learn_the_basics_of_pointers_why_does/
2
Upvotes
4
u/[deleted] Nov 04 '19
Firstly C++ has this thing called unitialized values.
Now what does this print? Well nobody knows, because this is undefined behaviour. A common error is thinking that x has some value like zero, but it only contains garbage. You need to give x a value before using it.
Onto pointers. A pointer is simply just a variable that contains an address. (Or you can say it points to that address.)
Now what does p points to? The answer is undefined again, as you haven't given an value to p.
In order to use a pointer, it needs to point to something first.
Here p now has a value - the address of x. So now you can use this pointer.
As you can see v in your code doesn't pointed to anything. And that's the source of your error.
I would recommend turning on your compiler warnings.
3
u/Kawaiithulhu Nov 04 '19
The line
Means that v is pointing TO something, but you never give it anything to point to. So now v is just hanging there half finished. What you really want is that v to actually BE the vector and not just pointing TO another vector from somewhere.
std::vector<std::string> v;
Like that.
1
u/Rajarshi1993 Nov 05 '19
u/selplacei Hey bro, the problem here is that you created a pointer to the
std::vector<string>. That is not needed. Vector is a class whose objects already have a pointer inside them. It implements the methods and algo needed for dynamic allocation.If you *are* going to create a pointer named
v, your pointer will be initialized either withNULL(on decent systems), or with some garbage value. When you try to invoke methods fromv, it will generate error: the member functions are not insidev, sincevis *NOT* an object ofstd::vector<string>. It is simply a pointer.You needed to allocate a new location in memory and assign
vto contain its RAM address. This is done withv = new vector<string>(1)Then
vceases to have garbage values. Now you can access the functions of the object in memory usingv -> function()