Temporarily not destroyed at the end of the statement

Is this behavior guaranteed all the time? The code below creates a char * pointer using a temporary unique_ptr. I thought unique_ptr should be destroyed at the end of the statement. To my surprise, char * still points to actual 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; 
+4
source share
3 answers

This causes undefined behavior. Undefined behavior means that everything can happen, including if it works. The temporary unique_ptr actually destroyed and as a result frees up a 100-element char array. You read and write to a memory location that is no longer allocated to you.

It so happened that the memory indicated by x was not allocated or read / written for something else by the time you work with it. But this memory has already been freed by the temporary unique_ptr , so you shouldn't mess with it.

Just don't do it. If you want to keep the array, but not unique_ptr , use release() .

+11
source

It is true that x indicates allocated memory, but this memory was freed at the end of the instruction, and the fact that now x indicates illegal memory, and an attempt to use it causes undefined behavior.

The program works because memory was not assigned to another process. But there is no guarantee that memory will not be assigned to another process.

Read this best explanation from @Eric Lippert here:

+1
source

Since you did not assign a variable of type unique_ptr , you created a temporary one. Memory is freed as soon as x initialized before Fill is called at all.

Just do the following:

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

As others said, itโ€™s just luck that your program didnโ€™t work. Failures are rarely guaranteed.

+1
source

All Articles