简体   繁体   中英

pointer with delete that does not reference dynamically allocated memory

It is possible to use a pointer with delete that does not reference dynamically allocated memory. Justify why or why not with an example.

In my example, I am doing this:

int *ptr; delete [] ptr;

The behavior of delete 'ing something that wasn't returned by new , and is not nullptr , is undefined . The pointer that you delete was not returned by new and is not nullptr , so the behavior of your program is undefined .

The value of a default-initialized pointer with automatic storage duration is indeterminate . Reading an indeterminate value has undefined behavior . Your program reads the indeterminate value of the pointer. The behavior of your program is undefined .

This snippet is undefined behaviour, since this does not initialize the pointer to nullptr .

The only pointers that can be used with delete operator are those that are given by new operator or null pointers. See

its value must be either null or pointer to a non-array object created by a new-expression, or a pointer to a base subobject of a non-array object created by a new-expression. If expression is anything else, including if it is a pointer obtained by the array form of new-expression, the behavior is undefined.

https://en.cppreference.com/w/cpp/language/delete

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM