Search code examples
c++unique-ptr

What is wrong with this use of std::unique_ptr that gives invalid pointer error?


Here is the code:

https://onlinegdb.com/BksirkDxw

I copy the same code here:

#include <iostream>
#include <memory>

using namespace std;

class cA{
    public: 
    cA(){}
    ~cA(){}
};
int main()
{
    std::unique_ptr<cA> qq(new cA[200]);
    
    cout << "OK" << endl;

    return 0;
}

Result:

OK                                                                                                                    
*** Error in `./a.out': free(): invalid pointer: 0x00000000014f4c28 ***                                               
Aborted (core dumped) 

Just doing new, and nothing more interesting.

Why do I get invalid pointer error?


Solution

  • Your code has undefined behavior. You're specifying the std::unique_ptr as containing single object, but you're initializing it with an array. You should specify the template argument as array; otherwise std::unique_ptr would try to call delete but not delete[] to destroy the object and deallocate the memory.

    std::unique_ptr<cA[]> qq(new cA[200]);