Home > Backend Development > C++ > Is Deleting a Void Pointer in C Safe?

Is Deleting a Void Pointer in C Safe?

Linda Hamilton
Release: 2024-12-16 21:19:15
Original
883 people have browsed it

Is Deleting a Void Pointer in C   Safe?

Pitfalls of Deleting a Void Pointer

Imagine the following code snippet:

void* my_alloc(size_t size)
{
    return new char[size];
}

void my_free(void* ptr)
{
    delete[] ptr;
}
Copy after login

Is it safe to delete the void pointer, ptr, in this manner?

Answer:

As per the C Standard, this is a treacherous practice. Section 5.3.5/3 reads as follows:

"In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand's dynamic type and the static type shall have a virtual destructor or the behavior is undefined. In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined."

The footnote following this passage further emphasizes:

"This implies that an object cannot be deleted using a pointer of type void* because there are no objects of type void."

Hence, deleting via a void pointer is strictly forbidden as it can result in unpredictable behavior.

The above is the detailed content of Is Deleting a Void Pointer in C Safe?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template