Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Temporary not getting destructed at the end of the statement

Tags:

c++

c++11

Is this behaviour guaranteed all the time ? The code below creates a char* pointer using temporary unique_ptr. I thought the unique_ptr should get destructed at the end of the statement. To my surprise, the char* still points to valid memory.

void Fill(char* str, long len)
{
    for(int i = 0; i < len; ++i)
        str[i] = 'a';
}

char* x = std::unique_ptr<char[]>(new char[100]).get();

Fill(x, 100);

std::cout << x << std::endl;
like image 740
Jagannath Avatar asked Dec 12 '22 09:12

Jagannath


2 Answers

That is invoking undefined behavior. Undefined behavior means anything can happen, including having it appear to work. The temporary unique_ptr is in fact being destructed, and as a result deallocates the 100-element char array. You're reading and writing into a memory location that is not allocated to you anymore.

It just so happens that the memory pointed by x hasn't been allocated or read/written for something else by the time you're working with it. But that memory has been already deallocated by the temporary unique_ptr, so you're not supposed to mess with it.

Just do not do this. If you want to keep the array but not the unique_ptr, use release() instead.

like image 173
In silico Avatar answered Dec 29 '22 00:12

In silico


Since you haven't assigned to a variable of type unique_ptr, you have only created a temporary. The memory is freed as soon as x is initialized, before Fill is called at all.

Simply do this:

std::unique_ptr<char[]> x(new char[100]);

Fill(x.get(), 100);

As the others have said, it's just luck that your program didn't crash. Crashes are seldom guaranteed.

like image 20
Potatoswatter Avatar answered Dec 28 '22 22:12

Potatoswatter