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

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. Git 和 SVN之间的五个基本区别

    GIT不仅仅是个版本控制系统,它也是个内容管理系统(CMS),工作管理系统等.如果你是一个具有使用SVN背景的人,你需要做一定的思想转换,来适应GIT提供的一些概念和特征.所以,这篇文章的主要目的就是 ...

  2. Cordova了解

    概述 Cordova让我们可以使用HTML.JS以及CSS开发跨平台App的公共部分(整个App就是一个WebView或者或者嵌入到本地组件中),与原生API的交互通过Cordova插件实现. 安装配 ...

  3. _cdel stdcall

    __cdecl 是C Declaration的缩写(declaration,声明),表示C语言默认的函数调用方法:所有参数从右到左依次入栈,这些参数由调用者清除,称为手动清栈.被调用函数不会要求调用者 ...

  4. C语言的ELF文件格式学习

    最近的lab里面有ELF文件相关的,所以成这个几乎,学点ELF的东西. ELF,是一种文件格式.暂时,只看可执行文件的ELF文件格式. 首先,给出文件的格式的布局图: 光看这个很难理解,所以写一个小的 ...

  5. AfxEnableControlContainer()

    1)OLE(Object Linking and Embedding,对象连接与嵌入).是一种面向对象的技术,利用OLE可开发可重复使用的软件组件(COM). 2)ActiveX 控件是基于组件对象模 ...

  6. 算法_php猴子选大王_约瑟夫问题

    题目: n个猴子围坐一圈,从第一个猴子开始数,到第m个出列,求最后一个猴子的编号. 分析: 首先想到循环,然后队列,然后堆,所以用数组模拟一个循环的列表,下标为[0-(n-1)],下标+1整除m干掉元 ...

  7. 【git】error: Your local changes to the following files

    今天在服务器上git pull是出现以下错误: error: Your local changes to the following files would be overwritten by mer ...

  8. pragma comment的使用

    该宏放置一个注释到对象文件或者可执行文件. #pragma comment( comment-type [,"commentstring"] ) comment-type是一个预定 ...

  9. Windows 7安装教程(详细图解)

    早前向大家介绍了Windows XP的安装教程,今天思齐再来介绍一下Windows 7的安装教程,Windows 7在安装上相对以前的Windows操作系统都要简单一些,这一点对于尤其是非专业用户来说 ...

  10. 利用 Windows Azure 实现“云优先”

    根据 IDC 的调查,云计算无疑为我们的合作伙伴提供了巨大的机会,预计到 2016 年,全球企业将在公共云服务上耗资 980 亿美元.在今天的休斯敦全球合作伙伴大会上,我们非常高兴能与合作伙伴共同寻求 ...