简体   繁体   English

带删除的指针,不引用动态分配的 memory

[英]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.可以使用不引用动态分配的 memory 的delete指针。 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 . delete的行为不是由new返回的,也不是nullptr ,是undefined The pointer that you delete was not returned by new and is not nullptr , so the behavior of your program is undefined .delete的指针不是由new返回的,也不是nullptr ,因此您的程序的行为是未定义的。

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 .这个片段是未定义的行为,因为它不会初始化指向nullptr的指针。

The only pointers that can be used with delete operator are those that are given by new operator or null pointers.唯一可以与delete运算符一起使用的指针是那些由new运算符或 null 指针给出的指针。 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.它的值必须是 null 或指向由 new 表达式创建的非数组 object 的指针,或指向由 new 表达式创建的非数组 object 的基本子对象的指针。 If expression is anything else, including if it is a pointer obtained by the array form of new-expression, the behavior is undefined.如果 expression 是其他任何东西,包括如果它是通过 new-expression 的数组形式获得的指针,则行为未定义。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 delete []运算符是否与通过指针返回的动态分配内存一起使用? - Does the delete[] operator work with dynamically allocated memory returned through a pointer? 我可以删除先前动态分配但具有不同指针的内存吗? - Can I delete a memory previously allocated dynamically, but with a different pointer? 交换指针后删除动态分配的 memory - Delete dynamically allocated memory after swapping its pointer 使用动态分配的内存(指针) - working with dynamically allocated memory (pointer) 默认情况下,从动态分配的解除引用指针初始化非const引用函数参数会产生内存泄漏吗? - Does default-initializing a non-const reference function parameter from a dynamically allocated dereferenced pointer create a memory leak? 何时删除动态分配的内存 - When to delete dynamically allocated memory 删除openGL中动态分配的内存 - delete dynamically allocated memory in openGL 引用动态分配变量vs指向相同动态分配变量的指针? - Reference to a dynamically allocated variable vs Pointer to the same dynamically allocated variable? cvrelease是否会删除分配的内存? - does cvrelease delete the allocated memory? 如何删除指向动态分配对象的智能指针? - How to delete smart pointer to dynamically allocated object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM