在 C++ 中删除指针
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13223399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Deleting a pointer in C++
提问by leopic
Context: I'm trying to wrap my head around pointers, we just saw them a couple of weeks ago in school and while practicing today I ran into a silly? issue, it can be super straightforward to you but I have little to none programming experience.
背景:我正试图围绕指针进行思考,几周前我们刚刚在学校看到它们,今天练习时我遇到了一个傻瓜?问题,这对您来说可能非常简单,但我几乎没有编程经验。
I've seen quite a few questions over in SO about deleting pointers but they all seem to be related to deleting a class and not a 'simple' pointer (or whatever the proper term might be), here's the code I'm trying to run:
我在 SO 中看到了很多关于删除指针的问题,但它们似乎都与删除类有关,而不是“简单”指针(或任何适当的术语),这是我正在尝试的代码跑:
#include <iostream>;
using namespace std;
int main() {
int myVar,
*myPointer;
myVar = 8;
myPointer = &myVar;
cout << "delete-ing pointers " << endl;
cout << "Memory address: " << myPointer << endl;
// Seems I can't *just* delete it, as it triggers an error
delete myPointer;
cout << "myPointer: " << myPointer << endl;
// Error: a.out(14399) malloc: *** error for object 0x7fff61e537f4:
// pointer being freed was not allocated
// *** set a breakpoint in malloc_error_break to debug
// Abort trap: 6
// Using the new keyword befor deleting it works, but
// does it really frees up the space?
myPointer = new int;
delete myPointer;
cout << "myPointer: " << myPointer << endl;
// myPointer continues to store a memory address.
// Using NULL before deleting it, seems to work.
myPointer = NULL;
delete myPointer;
cout << "myPointer: " << myPointer << endl;
// myPointer returns 0.
}
So my questions are:
所以我的问题是:
- Why won't the first case work? Seems the most straightforward use to use and delete a pointer? The error says the memory wasn't allocated but 'cout' returned an address.
- On the second example the error is not being triggered but doing a cout of the value of myPointer stillreturns a memory address?
- Does #3 really work? Seems to work to me, the pointer is no longer storing an address, is this the proper way to delete a pointer?
- 为什么第一个案例不起作用?使用和删除指针似乎是最直接的用法?该错误表示内存未分配但 'cout' 返回了一个地址。
- 在第二个例子中,错误没有被触发,但是对 myPointer 的值进行 cout仍然返回一个内存地址?
- #3 真的有效吗?似乎对我有用,指针不再存储地址,这是删除指针的正确方法吗?
Sorry for the long question, wanted to make this as clear as possible, also to reiterate, I have little programming experience, so if someone could answer this using layman's terms, it would be greatly appreciated!
对不起,这个问题很长,想尽可能清楚地说明这一点,还要重申,我几乎没有编程经验,所以如果有人能用外行的术语回答这个问题,将不胜感激!
回答by Anirudh Ramanathan
1 & 2
1 & 2
myVar = 8; //not dynamically allocated. Can't call delete on it.
myPointer = new int; //dynamically allocated, can call delete on it.
The first variable was allocated on the stack. You can call delete only on memory you allocated dynamically (on the heap) using the new
operator.
第一个变量分配在堆栈上。您只能在使用new
操作符动态分配的内存(在堆上)调用 delete 。
3.
3.
myPointer = NULL;
delete myPointer;
The above did nothing at all. You didn't free anything, as the pointer pointed at NULL.
上面什么都没做。你没有释放任何东西,因为指针指向 NULL。
The following shouldn't be done:
不应该做以下事情:
myPointer = new int;
myPointer = NULL; //leaked memory, no pointer to above int
delete myPointer; //no point at all
You pointed it at NULL, leaving behind leaked memory (the new int you allocated).
You should free the memory you were pointing at. There is no way to access that allocated new int
anymore, hence memory leak.
您将其指向 NULL,留下泄漏的内存(您分配的新 int)。你应该释放你指向的内存。无法再访问分配的内容new int
,因此内存泄漏。
The correct way:
正确的方法:
myPointer = new int;
delete myPointer; //freed memory
myPointer = NULL; //pointed dangling ptr to NULL
The better way:
更好的方法:
If you're using C++, do notuse raw pointers. Use smart pointersinstead which can handle these things for you with little overhead. C++11 comes with several.
回答by salgadokk
I believe you're not fully understanding how pointers work.
When you have a pointer pointing to some memory there are three different things you must understand:
- there is "what is pointed" by the pointer (the memory)
- this memory address
- not all pointers need to have their memory deleted: you only need to delete memory that was dynamically allocated (used new
operator).
我相信你没有完全理解指针的工作原理。
当您有一个指向某个内存的指针时,您必须了解三件不同的事情:
- 指针(内存)“指向了什么”
- 这个内存地址
- 并非所有指针都需要删除它们的内存:您只需要需要删除动态分配的内存(使用new
运算符)。
Imagine:
想象:
int *ptr = new int;
// ptr has the address of the memory.
// at this point, the actual memory doesn't have anything.
*ptr = 8;
// you're assigning the integer 8 into that memory.
delete ptr;
// you are only deleting the memory.
// at this point the pointer still has the same memory address (as you could
// notice from your 2nd test) but what inside that memory is gone!
When you did
当你做
ptr = NULL;
// you didn't delete the memory
// you're only saying that this pointer is now pointing to "nowhere".
// the memory that was pointed by this pointer is now lost.
C++ allows that you try to delete
a pointer that points to null
but it doesn't actually do anything, just doesn't give any error.
C++ 允许您尝试delete
指向指向的指针,null
但它实际上并没有做任何事情,只是不给出任何错误。
回答by user3728501
Pointers are similar to normal variables in that you don't need to delete them. They are removed from memory at the end of a functions execution and/or the end of the program.
指针类似于普通变量,因为您不需要删除它们。它们在函数执行结束和/或程序结束时从内存中删除。
You can however use pointers to allocate a 'block' of memory, for example like this:
但是,您可以使用指针来分配内存“块”,例如:
int *some_integers = new int[20000]
This will allocate memory space for 20000 integers. Useful, because the Stack has a limited size and you might want to mess about with a big load of 'ints' without a stack overflow error.
这将为 20000 个整数分配内存空间。很有用,因为堆栈的大小有限,您可能想要在没有堆栈溢出错误的情况下处理大量“整数”。
Whenever you call new, you should then 'delete' at the end of your program, because otherwise you will get a memory leak, and some allocated memory space will never be returned for other programs to use. To do this:
每当你调用 new 时,你应该在你的程序结束时“删除”,否则你会得到内存泄漏,并且一些分配的内存空间将永远不会返回给其他程序使用。去做这个:
delete [] some_integers;
Hope that helps.
希望有帮助。
回答by fonZ
There is a rule in C++, for every newthere is a delete.
C++ 中有一个规则,每一个new都有一个delete。
- Why won't the first case work? Seems the most straightforward use to use and delete a pointer? The error says the memory wasn't allocated but 'cout' returned an address.
- 为什么第一个案例不起作用?使用和删除指针似乎是最直接的用法?该错误表示内存未分配但 'cout' 返回了一个地址。
new is never called. So the address that cout prints is the address of the memory location of myVar, or the value assigned to myPointer in this case. By writing:
new 永远不会被调用。所以 cout 打印的地址就是 myVar 的内存位置的地址,或者在这种情况下分配给 myPointer 的值。通过写作:
myPointer = &myVar;
you say:
你说:
myPointer = The address of where the data in myVar is stored
myPointer = myVar 中数据的存储地址
- On the second example the error is not being triggered but doing a cout of the value of myPointer still returns a memory address?
- 在第二个例子中,错误没有被触发,但是对 myPointer 的值进行 cout 仍然返回一个内存地址?
It returns an address that points to a memory location that has been deleted. Because first you create the pointer and assign its value to myPointer, second you delete it, third you print it. So unless you assign another value to myPointer, the deleted address will remain.
它返回一个指向已删除内存位置的地址。因为首先创建指针并将其值赋给 myPointer,然后删除它,第三次打印它。因此,除非您为 myPointer 分配另一个值,否则已删除的地址将保留。
- Does #3 really work? Seems to work to me, the pointer is no longer storing an address, is this the proper way to delete a pointer?
- #3 真的有效吗?似乎对我有用,指针不再存储地址,这是删除指针的正确方法吗?
NULL equals 0, you delete 0, so you delete nothing. And it's logic that it prints 0 because you did:
NULL 等于 0,你删除 0,所以你什么也不删除。它打印 0 的逻辑是因为你做了:
myPointer = NULL;
which equals:
这等于:
myPointer = 0;
回答by Hakan Serce
- You are trying to delete a variable allocated on the stack. You can not do this
- Deleting a pointer does not destruct a pointer actually, just the memory occupied is given back to the OS. You can access it untill the memory is used for another variable, or otherwise manipulated. So it is good practice to set a pointer to NULL (0) after deleting.
- Deleting a NULL pointer does not delete anything.
- 您正在尝试删除分配在堆栈上的变量。你不可以做这个
- 删除指针实际上并不会破坏指针,只是将占用的内存返还给操作系统。您可以访问它,直到内存用于另一个变量,或以其他方式进行操作。因此,在删除后将指针设置为 NULL (0) 是一种很好的做法。
- 删除 NULL 指针不会删除任何内容。
回答by Casper Beyer
int value, *ptr;
value = 8;
ptr = &value;
// ptr points to value, which lives on a stack frame.
// you are not responsible for managing its lifetime.
ptr = new int;
delete ptr;
// yes this is the normal way to manage the lifetime of
// dynamically allocated memory, you new'ed it, you delete it.
ptr = nullptr;
delete ptr;
// this is illogical, essentially you are saying delete nothing.