dynamically allocated string arrays failed to be deallocated

前端 未结 2 615
萌比男神i
萌比男神i 2020-12-21 14:01

I have the following piece of code:

string * p = new string[8];
cout<

which seems ok to me but failed

相关标签:
2条回答
  • 2020-12-21 14:58

    Yap. new [] pairs with delete []. free()ing causes undefined behavior.

    0 讨论(0)
  • 2020-12-21 14:59

    First of all, when you use new you need to use delete, not free(). In fact, you should really never use free() or malloc() in C++. A good explanation for why you should never mix new and free or malloc() and delete is that new and delete call the constructor and destructor, free() and malloc() have nothing to do with that, they just allocate and deallocate memory, especially for built in classes this is bad because you don't know what is supposed to happen in std::string's destructor or constructor, it might be possible to make it work with your own built in class (but don't do it).

    You can replace your code with this:

    string * p = new string[8];
    cout<<sizeof(p)<<endl;
    delete [] p;  
    

    In the end, I would suggest you use a built in data type like std::vector or std::array. They are much more C++-ish than a standard old C array.

    0 讨论(0)
提交回复
热议问题