背景:我正试图将我的头包裹在指针上,我们几周前在学校看到它们,今天在练习时我遇到了一个傻子?问题,这对您来说可能非常简单,但我几乎没有编程经验。
我在 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.
}
所以我的问题是:
- 为什么第一个案例不起作用?使用和删除指针似乎是最直接的用法?该错误表示未分配内存,但“cout”返回了一个地址。
- 在第二个示例中,错误没有被触发,但是对 myPointer 的值进行 cout仍然返回内存地址?
- #3真的有用吗?似乎对我有用,指针不再存储地址,这是删除指针的正确方法吗?
很抱歉这个问题很长,想让这个尽可能清楚,也重申一下,我没有什么编程经验,所以如果有人可以用外行的术语回答这个问题,将不胜感激!