http://www.bogotobogo.com/cplusplus/CppCrashDebuggingMemoryLeak.php

Incorrect Memory Usage and Corrupted Memory

Here are the primary sources of the memory related problems.

  1. Using memory not initialized
  2. Using memory that we do not own
  3. Using more memory than allocated (buffer overruns)
  4. Using faulty heap memory management
Accessing NULL pointer - invalid object
访问空指针-无效对象

When we try to access a method of an object using a NULL pointer, our program crashes.

Here is a typical example of accessing an object with invalid pointer.

#include <iostream>

using namespace std;

class A
{
int value;
public:
void dumb() const {cout << "dumb()\n";}
void set(int x) {cout << "set()\n"; value=x;}
int get() const {cout << "get()\n"; return value;}
}; int main()
{
A *pA1 = new A;
A *pA2 = NULL; pA1->dumb();
pA1->set(10);
pA1->get();
pA2->dumb();
pA2->set(20);
pA2->get(); return 0;
}

Output from the run:

dumb()
set()
get()
dumb()
set()

We have three member function of a class A, "dumb()", "set()", and "get()". Pointers to A object are calling the methods of A. There is no problem calling those methods with properly allocated pointer pA1. However, the code crashes at the line:

pA2->set(20);

Why?
In the line, "set(20)" is invoked for a NULL pA2, it crashes when we try to access member variables of A class while there is no problem in calling "dumb()" with the same NULL pointer to the A object.

Invoking a method with an illegal object pointer is the same as passing an illegal pointer to a function. A crash happens when any member variable is accessed in the called method. In other words, the "set(20)" tries to access a member variable "value" but "dumb()" method does not.

If a pointer is a dangling pointer (pointing to memory that has already been freed), or to a memory location outside of current stack or heap bounds, it is referring to memory that is not currently possessed by the program. And using such pointer usually leads to a program crash.

Dangling Pointer
悬垂指针

A dangling pointer arises when a code uses a memory resource after it has been freed as in the example below.

struct X
{
int data;
}; int foo()
{
struct X *pX;
pX = (struct X *) malloc(sizeof (struct X));
pX->data = 10;
free(pX);
...
return pX->data;
}

The function "foo()" returns a member of struct X by using a pointer "pX" that has already released its memory. There is a chance that the memory block to which xp points has been overwritten with a different value. In the worst case, it may be deep into other places until it shows some symptoms. Dangling pointers are a constant source of headaches for C/C++ programs.

Uninitialized Pointer
为初始化指针

Another common mistake is trying to access uninitialized memory as the example below.

void fooA()
{
int *p;
*p = 100;
}

Most of the implementation of compiler, this triggers "segmentation violation."

As another example, the code below trying to free the pointer "p" which has not been initialized.

void fooB()
{
int *p;
free(p);
}

The outcome of this error is actually undefined, in other words, anything can happen.

Deallocation Error
释放错误

Freeing a memory which has already been freed is another example of memory error.

void fooA()
{
char *p;
p = (char *)malloc(100);
cout << "free(p)\n";
free(p);
cout << "free(p)\n";
free(p);
}

This type of error results in undefined behavior, it may crash or it may be passed unnoticed.

Not calling derived class destructor
ParentClass *pObj = new ChildClass;
...
delete pObj;

In the above example, coder's intention is do free the memory allocated for Child class object. However, because the type of "pObj" is a pointer to a Parent class, it deletes Parent object leaving the memory allocated for the Child object untouched. So, the memory leak.

In this case, we need to use a virtual destructor to avoid this problem. The ~ParentClass() is called and then the destructor for Child class ~ChildClass() is called at run time because it is a virtual destructor. If it is not declared virtual, then only the ~ParentClass() is called leaving any allocated memory from the ChildClass to persist and leak.

Buffer Overflow
缓冲区溢出

Depending on the length of the string, it may be attempting to write where the memory is not alloacted (void * memcpy ( void * destination, const void * source, size_t sz ).

char *s = (char *)malloc(128*sizeof(char));
memcpy(s, str, str_len);

As another example, when we try to copy a string, we need to consider the null character at the end of the string.

char *p = (char *)malloc(strlen(str));
strcpy(p, str);

In the code, we need to change the strlen(str) to strlen(str)+1.

【转】C++ Incorrect Memory Usage and Corrupted Memory(模拟C++程序内存使用崩溃问题)的更多相关文章

  1. Shell script for logging cpu and memory usage of a Linux process

    Shell script for logging cpu and memory usage of a Linux process http://www.unix.com/shell-programmi ...

  2. 5 commands to check memory usage on Linux

    Memory Usage On linux, there are commands for almost everything, because the gui might not be always ...

  3. SHELL:Find Memory Usage In Linux (统计每个程序内存使用情况)

    转载一个shell统计linux系统中每个程序的内存使用情况,因为内存结构非常复杂,不一定100%精确,此shell可以在Ghub上下载. [root@db231 ~]# ./memstat.sh P ...

  4. Why does the memory usage increase when I redeploy a web application?

    That is because your web application has a memory leak. A common issue are "PermGen" memor ...

  5. Reducing and Profiling GPU Memory Usage in Keras with TensorFlow Backend

    keras 自适应分配显存 & 清理不用的变量释放 GPU 显存 Intro Are you running out of GPU memory when using keras or ten ...

  6. GPU Memory Usage占满而GPU-Util却为0的调试

    最近使用github上的一个开源项目训练基于CNN的翻译模型,使用THEANO_FLAGS='floatX=float32,device=gpu2,lib.cnmem=1' python run_nn ...

  7. Memory usage of a Java process java Xms Xmx Xmn

    http://www.oracle.com/technetwork/java/javase/memleaks-137499.html 3.1 Meaning of OutOfMemoryError O ...

  8. Redis: Reducing Memory Usage

    High Level Tips for Redis Most of Stream-Framework's users start out with Redis and eventually move ...

  9. detect data races The cost of race detection varies by program, but for a typical program, memory usage may increase by 5-10x and execution time by 2-20x.

    小结: 1. conflicting access 2.性能危害 优化 The cost of race detection varies by program, but for a typical ...

随机推荐

  1. 转:configure/make/make install的作用 linux 安装 卸载 make uninstall

    这些都是典型的使用GNU的AUTOCONF和AUTOMAKE产生的程序的安装步骤. ./configure 是用来检测你的安装平台的目标特征的.比如它会检测你是不是有CC或GCC,并不是需要CC或GC ...

  2. ubuntu PATH 出错修复

    我的 ubuntu10.10设置交叉编译环境时,PATH 设置错误了,导致无法正常启动,错误情况如下: { PATH:找不到命令ubuntu2010@ubuntu:~$ ls命令 'ls' 可在 '/ ...

  3. cxf利用接口规范写法发布webservice

    package cn.itcast.cxf; import javax.jws.WebService; @WebService public interface IHelloService { pub ...

  4. ubuntu截图工具

    ubuntu截图工具   首先,我们用apt-get  install 去安装一个,scrot 主要用在命令行下,它使用 imlib2 库来抓取并保存图像                 sudo a ...

  5. Android设计模式系列(1)--SDK源码之组合模式

    Android中对组合模式的应用,可谓是泛滥成粥,随处可见,那就是View和ViewGroup类的使用.在android UI设计,几乎所有的widget和布局类都依靠这两个类.组合模式,Compos ...

  6. Bulk Load-HBase数据导入最佳实践

    一.概述 HBase本身提供了非常多种数据导入的方式,通常有两种经常使用方式: 1.使用HBase提供的TableOutputFormat,原理是通过一个Mapreduce作业将数据导入HBase 2 ...

  7. ocr 识别 github 源码

    参考 [1] https://github.com/eragonruan/text-detection-ctpn [2] https://github.com/senlinuc/caffe_ocr [ ...

  8. spring in action 8.1 使用Spring web flow

    一.说明 Spring Web Flow是spring MVC的扩展,它支持基于流程的应用程序,他将流程的定义和实现流程行为的类和视图分离开来. 1.1 spring中配置web flow,目前需要在 ...

  9. 基于Java Netty框架构建高性能的Jt808协议的GPS服务器(转)

    原文地址:http://www.jt808.com/?p=971 使用Java语言开发一个高质量和高性能的jt808 协议的GPS通信服务器,并不是一件简单容易的事情,开发出来一段程序和能够承受数十万 ...

  10. CYQ学习主要摘要3

    1:MAction:增加ResetTable功能  增加ResetTable功能:减少New MAction的个数2:MAction:增加在Update/Insert/Fill/ResetTable失 ...