Alex Rivera | Logout

deleting a buffer through a different type of pointer?

Asked 2008-09-16T10:01:00.747
10

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?

Edit
Report

1 Answer

0

While this should work, I don't think you can guarantee it to be safe because the SOME_STRUCT is not a char* (unless it's merely a typedef).

Additionally, since you're using different types of references, if you continue to use the *p access, and the memory has been deleted, you will get a runtime error.

answered 2008-09-16T10:07:19.577

Your Answer