这文章是早期闲得用英文写的,删除了怪可惜的,贴出来证明自己会英文算了。。。

Occasionally,on stackoverflow.com,I found a classic problem which is age-old but never to be out-dated,that is,the undefined behaviour occurred by reusing the pointer which was just deleted.

The code below may be a good example.(This piece of code refers to here)


1 #include <iostream>
2 class MyClass
3 {
4 public:
5 int a;
6 MyClass() : a(10)
7 {
8 std::cout << "constructor rann";
9 }
10 void method(std::string input_)
11 {
12 std::cout << input_.c_str()<< "n";
13 }
14 ~MyClass()
15 {
16 std::cout << "destructor rann";
17 }
18 };
19 int main()
20 {
21 MyClass* ptr = new MyClass;
22 ptr->method("1");
23 delete ptr;
24 ptr->method("2.5");
25 }
26

I used CL.exe(Version 17.00) and g++(Version 4.6) to run this code.

This code outputs:

constructor ran

1

destructor ran

2.5

Actually,I also confronted a confusing problem like this one when I was a c++ beginner(Until now,I’m still green at c++).I fear that I couldn’t believe what happened if I didn’t test what the value of variable a was.

So I added

 cout<<a<<endl

to line 27 and this code outputs:

Constructor ran

1

destructor ran

2.5

-17891602

At that time, I realized that the memory allocated to ptr was actually deleted.

Well...now,let us look at the definition of delete from Wiki:

"The delete operator calls the destructor of the given argument, and returns memory allocated by new back to the heap.",and the description of deallocation from N3376:

"If the argument given to a deallocation function in the standard library is a pointer that is not the null pointer value, the deallocation function shall deallocate the storage referenced by the pointer, rendering invalid all pointers referring to any part of the deallocated storage. The effect of using an invalid pointer value is undefined."

As for our program,after deleting the storage referenced by ptr, the manipulation on ptr is undefined.Under our current condition,ptr points to the same data it pointed to before and calling methods on it just works “fine”, but it’s not what we want and what we expect because maybe at next second,the allocator will allocate this memory to someone else.So,there is a recommended common method to deal with this counterintuitive problem:

 delete ptr;
ptr = NULL;

In this way,you could ensure that you won’t incautiously reuse this pointer before a piece of new memory is reallocate-d to it.

In conclusion,I suggest that you shouldn’t rely on pointer type unless it’s necessary.In most cases,reference is enough for us to solve problems.

Deleted pointer causes undefined behaviour的更多相关文章

  1. C语言undefined behaviour未定义行为

    C语言中的未定义行为(Undefined Behavior)是指C语言标准未做规定的行为.同时,标准也从没要求编译器判断未定义行为,所以这些行为有编译器自行处理,在不同的编译器可能会产生不同的结果,又 ...

  2. Pointer arithmetic for void pointer in C

    http://stackoverflow.com/questions/3523145/pointer-arithmetic-for-void-pointer-in-c When a pointer t ...

  3. [Elixir009]像GenServer一样用behaviour来规范接口

    1.Behaviour介绍 Erlang/Elixir的Behaviour类似于其它语言中的接口(interfaces),本质就是在指定behaviours的模块中强制要求导出一些指定的函数,否则编译 ...

  4. zookeeper 学习笔记 (C语言版本)

    1.zookeeper简介 zookeeper是Hadoop的子项目,在大型分布式系统中,zookeeper封装好了一些复杂易出错的服务,提供简单易用的接口,给使用者提供高效稳定的服务.这些服务包括配 ...

  5. [搬运]CORBA中BOA和POA的含义

    先来BOA,搬自:http://www.cl.cam.ac.uk/research/dtg/attarchive/omniORB/doc/2.8/omniORB2/node6.html The Bas ...

  6. (C/C++) Interview in English - Points.

    Q: What is a dangling pointer? A: A dangling pointer arises when you use the address of an object af ...

  7. Why am I able to change the contents of const char *ptr?

    http://stackoverflow.com/questions/3228664/why-am-i-able-to-change-the-contents-of-const-char-ptr I ...

  8. Automake

    Automake是用来根据Makefile.am生成Makefile.in的工具 标准Makefile目标 'make all' Build programs, libraries, document ...

  9. [转]ARM/Thumb2PortingHowto

    src: https://wiki.edubuntu.org/ARM/Thumb2PortingHowto#ARM_Assembler_Overview When you see some assem ...

随机推荐

  1. 8QQ消息框

    1 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> < ...

  2. IOS支付宝支付出现6002问题的解决办法

    运行支付宝官方demo进行支付测试,会出现6002-网络连接错误,是因为以iOS9 SDK编译的工程会默认以SSL安全协议进行网络传输,即HTTPS,如果依然使用HTTP协议请求网络会报系统异常并中断 ...

  3. Sql Server数据库设计高级查询

    -------------------------------------第一章  数据库的设计------------------------------------- 软件开发周期:     (1 ...

  4. python基础:映射和集合类型

    python字典的迭代器遍历 字典有一个方法可以返回该字典的迭代器,这个方法就是: dict. iteritems() 当在字典中增加或者删除字典entry的时候,迭代器会失效的,类似于C++的stl ...

  5. 点击上下页,实现图片滚动的jquery代码

    <!DOCTYPE HTML><html><head><meta http-equiv="Content-Type" content=&q ...

  6. CSS自学笔记(11):CSS3背景和边框

    CSS3 背景 在CSS3中新增了多个关于背景的属性,可以让我们对背景有了更多更好的操作,减少用第三方工具对背景图片进行修改美化. CSS3中主要是通过定义backgrounp中的各个属性来控制背景( ...

  7. 动态加载Layout 与 论Activity、 Window、View的关系

    1)动态加载Layout的代码是 getWindow().setContentView(LayoutInflater.from(this).inflate(R.layout.main, null)); ...

  8. 修改默认的undo_retention参数设置

    昨天,一个朋友的数据库数据被误操作删除掉了,请求我帮忙进行恢复. 数据库版本是Oracle10g Release 2的,我首先想到的是使用Flashback Query进行闪回恢复,不幸的是ORA-0 ...

  9. 大型网站性能优化(页面(HTML)优化的方法)

    页面(HTML)优化的方法 除了语言层面上进行优化外,对Web开发,HTML的优化将很大程度上减轻服务器的负载,提高网站的性能 1). 减少HTTP请求数.打开网页,浏览器会发出很多请求,图片,脚本, ...

  10. 人生第一场组队赛---2014.8 zju monthly

    暑期集训中段就组了队,不过一直没机会打比赛 昨天kitkat突然发现了zju要搞月赛,我想了一下题目对于我这种渣实在是有点难,于是想到干脆打一次组队赛吧,跟队友商量了一下也同意了 12点---17点  ...