Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...