【转】C++ Incorrect Memory Usage and Corrupted Memory(模拟C++程序内存使用崩溃问题)
http://www.bogotobogo.com/cplusplus/CppCrashDebuggingMemoryLeak.php
Here are the primary sources of the memory related problems.
- Using memory not initialized
- Using memory that we do not own
- Using more memory than allocated (buffer overruns)
- Using faulty heap memory management
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.
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.
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.
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.
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.
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++程序内存使用崩溃问题)的更多相关文章
- 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 ...
- 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 ...
- SHELL:Find Memory Usage In Linux (统计每个程序内存使用情况)
转载一个shell统计linux系统中每个程序的内存使用情况,因为内存结构非常复杂,不一定100%精确,此shell可以在Ghub上下载. [root@db231 ~]# ./memstat.sh P ...
- 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 ...
- 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 ...
- GPU Memory Usage占满而GPU-Util却为0的调试
最近使用github上的一个开源项目训练基于CNN的翻译模型,使用THEANO_FLAGS='floatX=float32,device=gpu2,lib.cnmem=1' python run_nn ...
- 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 ...
- Redis: Reducing Memory Usage
High Level Tips for Redis Most of Stream-Framework's users start out with Redis and eventually move ...
- 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 ...
随机推荐
- CSDN日报20170401 ——《假设你还是“程序猿”,我劝你别创业!》
[程序人生]假设你还是"程序猿".我劝你别创业! 作者:北漂周 在IT这一行做得久了,会接触到无数让人哭笑不得的外行话. 「我们就差一个写代码的了」是当中典型的一种,之所以黑它.不 ...
- 解决Sping 框架 Controller@Value获取不到值
原因:要获取 int.properties 中的数据 但是 一直拿不到值 如下代码 使用这种方式注入 *.properties文件 <!-- 引入配置文件 --> <context: ...
- Python3 isprintable() 方法
描述 判断字符串中所有字符是否都是可打印字符(in repr())或字符串为空. Unicode字符集中“Other” “Separator”类别的字符为不可打印的字符(但不包括ASCII码中的空格( ...
- centos7下mysqldump+crontab自动备份数据库
1.创建文件夹(存放备份数据) mkdir /bak mkdir /bak/mysqldata 2.编写脚本 vi /usr/sbin/bakmysql.sh 脚本内容如下 DATE=`date +% ...
- js身份证验证算法
var validateIdCard=function (id, backInfo) { var info={ y: "1900", m: "01", d: & ...
- java中加密解密工具类
在工作中经常遇到需要加密.解密的场景.例如用户的手机号等信息,在保存到数据库的过程中,需要对数据进行加密.取出时进行解密. public class DEStool { private String ...
- php类自动载入
在编写面向对象(OOP) 程序时,很多开发者为每个类新建一个 PHP 文件. 这会带来一个烦恼:每个脚本的开头,都需要包含(include)一个长长的列表(每个类都有个文件). 在 PHP 5 中,已 ...
- 【iOS开发之Objective-C】书签管理器项目
1.项目 新建一个书签管理器的项目,能够存储书签的网址.中文名.星级.訪问量和权限信息.具有增.删.改.查和排序的功能. 2.找对象,抽象类 书签管理器,书签管理器.书签管理器-- 多读几次书是不是 ...
- Atitit.注册跟个登录功能的实现attilax总结obo
Atitit.注册跟个登录功能的实现attilax总结obo 1. 注册模块 2 1.1. 基本注册功能(用户名方式) 2 1.2. 动态ajax监测用户名重复 2 1.3. 注册手机验证 2 1.4 ...
- 安装wxWidgets遭遇的两大关卡
早就想体验wxWidgets.这学期的C++课,课时还算充裕.关键是弟子们的实践能跟得上,我希望能让他们也浅尝一把GUI开发. MFC能够选.但既然IDE都用CodeBlocks了.还是选wxWidg ...