Smart pointers - unique_ptr for a stack-allocated variable - c++

I have the following simple code, and I have not found a thread where smart pointers are used for this simple case, but rather copy objects:
int main()
{
int i = 1;
std::unique_ptr<int> p1(&i);
*p1 = 2;
return 0;
}
This results in _BLOCK_TYPE_IS_INVALID when the pointer goes out of scope. If I call p1.release(), the code works fine and I do not get this error. I thought such pointers are smart enough to handle dangling pointers?
An alternative would be if I had a copy of i, which does not give the above error:
std::unique_ptr<int> p1(new int(i));
What is the advantage of using smart pointers here, where I do not want to perform the local copy?
If I were to use a raw pointer:
int i = 1;
int *p1 = &i;
*p1 = 2;
I would not get an error, even if I don't code:
p1 = nullptr;

std::unique_ptrs are for handling dynamically allocated memory; they're said to take ownership of the pointer when you construct one.
Your int i; is on the stack, and thus isn't dynamically allocated; it's ownership can't be taken away from the stack. When the unique_ptr destructor tries to delete the pointer you gave it (because it thinks nobody owns it anymore), you get that error because delete can only be used for pointers created with new.
Given your short example, I don't know what context this is in... But you should use raw pointers (or make a copy, as you said) for stack-allocated variables.

The answer provided by #qzx is the main reason of the problem you've reported in your code
One additional thing about std::unique_ptr<> usage. You should always try to use std::make_unique<>() to create a std::unique_ptr. It sometimes help in using this pointer appropriately by providing appropriate compilation errors.
For example, if you change the above code with std::make_unique<> as
int i = 1;
std::unique_ptr<int> p1 = make_unique<int>(&i);
then most compiler will give error as
can't convert int* to int
It will help you to use a copy which creates a totally new integer whose ownership is taken by std::unique_ptr<>
int i = 1;
std::unique_ptr<int> p1 = make_unique<int>(i);
*p1 = 2;
This code works.

Related

Assigning unique_ptr to object

Noobie here trying to understand smart pointers. Why am I allowed to do this:
int *p1;
int var1 = 1;
p1 = &var1;
but not this:
std::unique_ptr<int> p2;
int var2 = 2;
p2 = &var2;
I get No viable overloaded '=' on the last line. Is there any way to create a unique_ptr without assigning it, create an int object, and THEN assign the unique_ptr to that object?
[Why am I not allowed to do this]:
std::unique_ptr<int> p2;
int var2 = 2;
p2 = &var2;
Because a unique pointer takes ownership of the bare pointer that it wraps, and when the unique pointer is destroyed, it will invoke the deleter on that pointer. You must never delete pointers to objects in automatic storage. That's a language rule, and if you don't follow the rule, then the behaviour of the program is undefined.
Hence, you must never transfer the ownership of a pointer to automatic (nor static, nor thread local) object to a smart pointer. You can never have ownership of such variables, so such ownership isn't yours to transfer.
Is there any way to create a unique_ptr without assigning it, create an int object, and THEN assign the unique_ptr to that object?
Yes. Example:
std::unique_ptr<int> p2;
p2 = std::make_unique<int>(2);
P.S. A dynamically allocating int is probably rarely useful.

Smart pointers to an object explicitly created object

I have read a lot of issues created in regard to this but was not able to answer my question.
I have created a class as follows -
class exampleClass{
public:
exampleClass(int n){
cout<<"Created Class"<<endl;
this->number = n;
}
~exampleClass(){
cout<<endl<<"This class is destroyed Now"<<endl;
}
template<typename t> t
addNum(t a, t b){
return a + b;
}
void print(){
cout<<this->number<<endl;
}
private:
int number;
};
and I make 2 shared_ptr(or for that matter unique_ptr, error is same) as follows -
int main(){
exampleClass* object = new exampleClass(60);
std::shared_ptr<exampleClass> p1(object);
std::shared_ptr<exampleClass> p2 (object);
p1->print();
}
Now the error it throws at the end is -
free(): double free detected in tcache 2
Aborted (core dumped)
I am not able to understand why the error at the end. Shouldn't the above code be equal to p2 =p1(in case of shared_ptr) or p2 = std::move(p1) for unique_ptr as both the pointers are for the same object?
TIA
PS - The title might be a little misleading or not accurate,but I did not know what exactly should be a title.
When you create a smart pointer, it will take ownership of the pointer, and deletes it when it goes out of scope (or when the last reference is done in case of a shared pointer).
When you create two smart pointers from the same raw pointer they both will delete the pointer at the end of their life, because they don't know about each other.
int main()
{
// Create a shared pointer with a new object
std::shared_ptr<exampleClass> p1 = std::make_shared<exampleClass>(60);
// Now you can safely create a second pointer from your existing one.
std::shared_ptr<exampleClass> p2 = p1;
p1->print();
p2->print();
}
When you create a shared_ptr from a raw pointer, it takes ownership of the raw pointer, and when the smart pointer goes out of scope, it will call delete on the owned resource. Giving the same raw pointer to 2 different shared_ptrs causes a double free, as both of them will try to free the resource.
If you need 2 shared_ptrs that share the same resource, you can copy the first one:
int main(){
exampleClass* object = new exampleClass(60);
std::shared_ptr<exampleClass> p1(object);
std::shared_ptr<exampleClass> p2 = p1;
}
This way they share ownership of the resource (sharaed_ptrs have an internal reference counter that tracks how many of them own a resource. When you copy a shared_ptr, the reference counter is incremented. When one goes out of scope, the reference counter is decremented. Only if the counter reaches zero is the resource freed) thus it will only be freed once, when the last shared_ptr owning the resource goes out of scope.
It's usually preferable to avoid explicitly writing out new and use make_shared, which does the allocation, creates the object for you and returns a shared_ptr that owns it:
auto object = std::make_shared<exampleClass>(60);
Some additional advanced reading in the topic, not strictly related to the question:
performance differences when using make_shared vs manually calling new: here
memory implications of using make_shared with weak_ptrs and large objects: here (Thanks for bringig this up #Yakk - Adam Nevraumont, this was new for me :))

C++ multiple unique pointers from same raw pointer

Consider my code below. My understanding of unique pointers was that only one unique pointer can be used to reference one variable or object. In my code I have more than one unique_ptr accessing the same variable.
It's obviously not the correct way to use smart pointers i know, in that the pointer should have complete ownership from creation. But still, why is this valid and not having a compilation error? Thanks.
#include <iostream>
#include <memory>
using namespace std;
int main()
{
int val = 0;
int* valPtr = &val;
unique_ptr <int> uniquePtr1(valPtr);
unique_ptr <int> uniquePtr2(valPtr);
*uniquePtr1 = 10;
*uniquePtr2 = 20;
return 0;
}
But still, why is this valid
It is not valid! It's undefined behaviour, because the destructor of std::unique_ptr will free an object with automatic storage duration.
Practically, your program tries to destroy the int object three times. First through uniquePtr2, then through uniquePtr1, and then through val itself.
and not having a compilation error?
Because such errors are not generally detectable at compile time:
unique_ptr <int> uniquePtr1(valPtr);
unique_ptr <int> uniquePtr2(function_with_runtime_input());
In this example, function_with_runtime_input() may perform a lot of complicated runtime operations which eventually return a pointer to the same object valPtr points to.
If you use std::unique_ptr correctly, then you will almost always use std::make_unique, which prevents such errors.
Just an addition to Christian Hackl's excellent answer:
std::unique_ptr was introduced to ensure RAII for pointers; this means, in opposite to raw pointers you don't have to take care about destruction yourself anymore. The whole management of the raw pointer is done by the smart pointer. Leaks caused by a forgotten delete can not happen anymore.
If a std::unique_ptr would only allow to be created by std::make_unique, it would be absolutely safe regarding allocation and deallocation, and of course that would be also detectable during compile time.
But that's not the case: std::unique_ptr is also constructible with a raw pointer. The reason is, that being able to be constructed with a hard pointer makes a std::unique_ptr much more useful. If this would not be possible, e.g. the pointer returned by Christian Hackl's function_with_runtime_input() would not be possible to integrate into a modern RAII environment, you would have to take care of destruction yourself.
Of course the downside with this is that errors like yours can happen: To forget destruction is not possible with std::unique_ptr, but erroneous multiple destructions are always possible (and impossible to track by the compiler, as C.H. already said), if you created it with a raw pointer constructor argument. Always be aware that std::unique_ptr logically takes "ownership" of the raw pointer - what means, that no one else may delete the pointer except the one std::unique_ptr itself.
As rules of thumb it can be said:
Always create a std::unique_ptr with std::make_unique if possible.
If it needs to be constructed with a raw pointer, never touch the raw pointer after creating the std::unique_ptr with it.
Always be aware, that the std::unique_ptr takes ownership of the supplied raw pointer
Only supply raw pointers to the heap. NEVER use raw pointers which point to local
stack variables (because they will be unavoidably destroyed automatically,
like valin your example).
Create a std::unique_ptr only with raw pointers, which were created by new, if possible.
If the std::unique_ptr needs to be constructed with a raw pointer, which was created by something else than new, add a custom deleter to the std::unique_ptr, which matches the hard pointer creator. An example are image pointers in the (C based) FreeImage library, which always have to be destroyed by FreeImage_Unload()
Some examples to these rules:
// Safe
std::unique_ptr<int> p = std::make_unique<int>();
// Safe, but not advisable. No accessible raw pointer exists, but should use make_unique.
std::unique_ptr<int> p(new int());
// Handle with care. No accessible raw pointer exists, but it has to be sure
// that function_with_runtime_input() allocates the raw pointer with 'new'
std::unique_ptr<int> p( function_with_runtime_input() );
// Safe. No accessible raw pointer exists,
// the raw pointer is created by a library, and has a custom
// deleter to match the library's requirements
struct FreeImageDeleter {
void operator() (FIBITMAP* _moribund) { FreeImage_Unload(_moribund); }
};
std::unique_ptr<FIBITMAP,FreeImageDeleter> p( FreeImage_Load(...) );
// Dangerous. Your class method gets a raw pointer
// as a parameter. It can not control what happens
// with this raw pointer after the call to MyClass::setMySomething()
// - if the caller deletes it, your'e lost.
void MyClass::setMySomething( MySomething* something ) {
// m_mySomethingP is a member std::unique_ptr<Something>
m_mySomethingP = std::move( std::unique_ptr<Something>( something ));
}
// Dangerous. A raw pointer variable exists, which might be erroneously
// deleted multiple times or assigned to a std::unique_ptr multiple times.
// Don't touch iPtr after these lines!
int* iPtr = new int();
std::unique_ptr<int> p(iPtr);
// Wrong (Undefined behaviour) and a direct consequence of the dangerous declaration above.
// A raw pointer is assigned to a std::unique_ptr<int> twice, which means
// that it will be attempted to delete it twice.
// This couldn't have happened if iPtr wouldn't have existed in the first
// place, like shown in the 'safe' examples.
int* iPtr = new int();
std::unique_ptr<int> p(iPtr);
std::unique_ptr<int> p2(iPtr);
// Wrong. (Undefined behaviour)
// An unique pointer gets assigned a raw pointer to a stack variable.
// Erroneous double destruction is the consequence
int val;
int* valPtr = &val;
std::unique_ptr<int> p(valPtr);
This example of code is a bit artificial. unique_ptr is not usually initialized this way in real world code. Use std::make_unique or initialize unique_ptr without storing raw pointer in a variable:
unique_ptr <int> uniquePtr2(new int);

double free or corruption with shared pointers

So the essence of my problem is this:
//Big.h
class Big{
public:
int a, b;
};
//Mini.h
class Big;
class Mini{
public:
Mini(float a, shared_ptr<Big> ptb):ma(a), me(-a), ptb(ptb){};
float ma, me;
shared_ptr<Big> ptb;
};
//main
int main(){
std::list<Mini> lm;
if(true){ //Or some sub function or rutin
Big big; big.a = 100; big.b = 200;
Mini derp(5, shared_ptr<Big>(&big));
lm.push_front(derp);
}
//Do something
};
Compiles fine but it gives a "double free or corruption" when exiting main (in the full program this is just a sub function)
I suspect the shared_ptr to big is being freed at some point and then again when exiting main, but I'm not sure and have no idea of how to fix it. Can someone please explain to me the reason of this error?
I red that I had to NULL the pointer to but I don't know where.
Or maybe I'm just using the wrong smart pointer or something like that?
Thanks
You're constructing a shared_ptr with a pointer to an existing object on the stack. Don't do that; that's not how shared_ptr is meant to be used. Ordinary stack objects should never be deleted or freed. The object it's pointing at is supposed to be on the heap, i.e. created using new or the equivalent.
The recommended way to create a shared_ptr is through make_shared:
auto p = make_shared<Big>();
or the old-fashioned way:
shared_ptr<Big> p(new Big);
Objects managed by a shared_ptr must be constructed in dynamic scope, i.e. allocated with new.
Big big;
big.a = 100;
big.b = 200;
Mini derp(5, shared_ptr<Big>(&big));
And here, you're shoving a pointer to an object that was constructed in automatic scope into a shared_ptr. shared_ptr now thinks it owns this object, and it gets to decide when it is going to delete it.
But when this object in automatic scope goes out of scope and gets destroyed, this will make this shared_ptr very, very sad.
Use new to construct this object, instead of constructing it in automatic scope.
The shared_ptr points to a stack object. You cannot free stack objects. Here's how to use shared_ptr:
auto big = std::make_shared<Big>();
big->a = 100;
big->b = 200;
Mini derp(5, big);
To correct your program, you need to allocate your Big object on the heap.
if(true){ //Or some sub function or rutin
auto big_shared_ptr = std::make_shared<Big>();
big->a = 100; big->b = 200;
Mini derp(5, big_shared_ptr);
lm.push_front(derp);
}
This way, the variable won't be destroyed when your if(true) block returns as well as when the shared_ptr is cleaned up - which would cause a double free.

Return pointer to data declared in function

I know this won’t work because the variable x gets destroyed when the function returns:
int* myFunction()
{
int x = 4;
return &x;
}
So how do I correctly return a pointer to something I create within the function, and what do I have to take care with? How do I avoid memory leaks?
I've also used malloc:
int* myFunction2()
{
int* x = (int*)malloc(sizeof int); *x = 4; return x;
}
How do you correctly do this - in C and C++?
For C++, you can use a smart pointer to enforce the ownership transfer. auto_ptr or boost::shared_ptr are good options.
Your second approach is correct. You just need to clearly document that the caller "owns" the result pointer, and is responsible for freeing it.
Because of this extra complexity, it is rare to do this for "small" types like int, though I'm assuming you just used an int here for the sake of an example.
Some people will also prefer to take a pointer to an already allocated object as a parameter, rather than allocating the object internally. This makes it clearer that the caller is responsible for deallocating the object (since they allocated it in the first place), but makes the call site a bit more verbose, so it's a trade-off.
For C++, in many cases, just return by value. Even in cases of larger objects, RVO will frequently avoid unnecessary copying.
One possibility is passing the function a pointer:
void computeFoo(int *dest) {
*dest = 4;
}
This is nice because you can use such a function with an automatic variable:
int foo;
computeFoo(&foo);
With this approach you also keep the memory management in the same part of the code, ie. you can’t miss a malloc just because it happens somewhere inside a function:
// Compare this:
int *foo = malloc(…);
computeFoo(foo);
free(foo);
// With the following:
int *foo = computeFoo();
free(foo);
In the second case it’s easier to forget the free as you don’t see the malloc. This is often at least partially solved by convention, eg: “If a function name starts with XY, it means that you own the data it returns.”
An interesting corner case of returning pointer to “function” variable is declaring the variable static:
int* computeFoo() {
static int foo = 4;
return &foo;
}
Of course this is evil for normal programming, but it might come handy some day.
C++ approach to avoid memory leaks. (at least when You ignore function output)
std::auto_ptr<int> myFunction() {
std::auto_ptr<int> result(new int(4));
return result;
}
Then call it:
std::auto_ptr<int> myFunctionResult = myFunction();
EDIT: As pointed out by Joel. std::auto_ptr has it's own drawbacks and generally should be avoided.
Instead std::auto_ptr You could use boost::shared_ptr (std::tr1::shared_ptr).
boost::shared_ptr<int> myFunction() {
boost::shared_ptr<int> result(new int(5));
return result;
}
or when use C++0x conforming compiler You can use std::unique_ptr.
std::tr1::unique_ptr<int> myFunction() {
std::tr1::unique_ptr<int> result(new int(5));
return result;
}
The main difference is that:
shared_ptr allows multiple instances of shared_ptr pointing to the same RAW pointer. It uses reference counting mechanism to ensure that memory will not be freed as long as at least one instance of shared_ptr exist.
unique_ptr allows only one instance of it holding pointer but have true move semantic unlike auto_ptr.
In C++, you should use new:
int *myFunction()
{
int blah = 4;
return new int(blah);
}
And to get rid of it, use delete:
int main(void)
{
int *myInt = myFunction();
// do stuff
delete myInt;
}
Note that I'm invoking the copy constructor for int while using new, so that the value "4" is copied onto the heap memory. The only way to get a pointer to something on the stack reliably is to copy it onto the heap by invoking new properly.
EDIT: As noted in another answer, you will also need to document that the pointer needs to be freed by the caller later on. Otherwise you might have a memory leak.
There is another approach - declare x static. In this case it will be located in data segment, not on stack, therefore it is available (and persistent) during the program runtime.
int *myFunction(void)
{
static int x = 4;
return &x;
}
Please note that assignment x=4 will be performed only on first call of myFunction:
int *foo = myFunction(); // foo is 4
*foo = 10; // foo is 10
*foo = myFunction(); // foo is 10
NB! Using function-scope static variables isn't tread-safe technique.
Your second code snippet is correct.
To help avoid memory leaks, I let the coding conventions help me.
xxxCreate() will allocate memory for xxx and initialize it.
xxxDelete() will destroy/corrupt xxx and free it.
xxxInit() will initialize xxx (never allocate)
xxxDestroy() will destroy/corrupt xxx (never free)
Additionally, I try to add the code to delete/destroy/free as soon as I add the code to create/init/malloc. It's not perfect, but I find that it helps me differentiate between items that need to be freed and those that don't, as well as reducing the likelihood that I will forget to free something at a later time.
Boost or TR1 shared pointers are generally the way to go. It avoids the copy overhead, and gives you semi-automatic deletion. So your function should look like:
boost::shared_ptr<int> myFunction2()
{
boost::shared_ptr<int> x = new int;
*x = 4;
return x;
}
The other option is just to allow a copy. That's not too bad if the object is small (like this one) or you can arrange to create the object in the return statement. The compiler will usually optimize a copy away if the object is created in the return statement.
I would try something like this:
int myFunction2b( int * px )
{
if( px )
{
*px = 4;
return 1;
}
// Choice 1: Assert or Report Error
// Choice 2: Allocate memory for x. Caller has to be written accordingly.
// My choice is 1
assert( 0 && "Argument is NULL pointer" );
return 0;
}
You're asking how to correctly return a pointer. That's the wrong question, because what you should be doing is using smart pointers rather than raw pointers. scoped_ptr and shared_ptr (available in boost and tr1) are good pointers to look at (e.g. here and here)
If you need the raw pointer for something (e.g. passing to a C function), the get() method will supply it.
If you must create raw pointers, e.g. for homework, then you can use malloc() (as you did) or new within a function, and hope you remember to de-allocate the memory (through free() and delete respectively) Or, in a slightly-less-likely-to-leak idiom, you can create the pointer with new, pass it to a function, and de-allocate with delete when you're done with it. Again, though, use smart pointers.