Home > Backend Development > C++ > Is it Safe to Delete Memory Allocated via `void*` in C ?

Is it Safe to Delete Memory Allocated via `void*` in C ?

DDD
Release: 2024-12-06 13:55:11
Original
1054 people have browsed it

Is it Safe to Delete Memory Allocated via `void*` in C  ?

Dangers of Deleting Via Void Pointers in C

Consider the following code snippet:

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

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

The question arises: is it safe to use my_free to delete a pointer allocated by my_alloc, given that my_alloc returns a void*?

Undefined Behavior

The answer is a resounding "no." Deleting via a void* is explicitly forbidden by the C Standard. Section 5.3.5/3 states:

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.

And its footnote adds:

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

Consequences

Deleting through a void* can lead to unpredictable and catastrophic consequences. The program may crash with a memory error, corrupt data, or produce erroneous results.

Therefore, it is imperative to always cast the pointer to the correct type before deleting it. In this case, the pointer should be cast to char* before passing it to delete[].

The above is the detailed content of Is it Safe to Delete Memory Allocated via `void*` in C ?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template