Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deleting a buffer through a different type of pointer?

Say I have the following C++:

char *p = new char[cb];
SOME_STRUCT *pSS = (SOME_STRUCT *) p;
delete pSS;

Is this safe according to the C++ standard? Do I need to cast back to a char* and then use delete[]? I know it'll work in most C++ compilers, because it's plain-ordinary-data, with no destructors. Is it guaranteed to be safe?

like image 862
Roger Lipscombe Avatar asked Sep 16 '08 10:09

Roger Lipscombe


1 Answers

It's not guaranteed to be safe. Here's a relevant link in the C++ FAQ lite:

[16.13] Can I drop the [] when deleting array of some built-in type (char, int, etc.)?

http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.13

like image 149
thudbang Avatar answered Sep 21 '22 21:09

thudbang