Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

c++ - dynamically allocated string arrays failed to be deallocated

I have the following piece of code:

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

which seems ok to me but failed with:

8
a.out(85837) malloc: *** error for object 0x7fb5b3403ae8: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6

Another test on an integer array worked. Is there anything special with c++ string?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...