文档章节

C++内存管理

SVD
 SVD
发布于 2015/11/11 22:32
字数 773
阅读 168
收藏 1
#include <iostream>
#include <stdlib.h>
using namespace std;

int main(void)
{
	int *p = new int[1000];
	if (NULL == p)
	{
		system("pause");
		return 0;
	}
	p[0] = 10;
	p[1] = 20;
	cout << p[0] <<","<<p[1]<< endl;
	delete []p;
	p = NULL;
	system("pause");
	return 0;

}

内存是一种资源,需要程序员学会分配和回收。

new-allocate space dynamically on the heap(free store).

new-returns the address of the allocated memory.

Use pointers to reference the memory allocated on the heap.

delete-to deallocate memory on the heap.

garbage-created when we can no longer access previously allocated memory on the heap.

dangling pointer(迷途指针)-a pointer that no longer points to something valid on the heap.

指针存储在stack,指针指向的值存储在heap.所以需要分析内存的这两种结果模型的特点:

Stack vs Heap

So far we have seen how to declare basic type variables such as int, double, etc, and complex types such as arrays and structs. The way we have been declaring them so far, with a syntax that is like other languages such as MATLAB, Python, etc, puts these variables on the stack in C.

  • The Stack

What is the stack? It's a special region of your computer's memory that stores temporary variables created by each function (including the main() function). The stack is a "FILO" (first in, last out) data structure, that is managed and optimized by the CPU quite closely. Every time a function declares a new variable, it is "pushed" onto the stack. Then every time a function exits, all of the variables pushed onto the stack by that function, are freed (that is to say, they are deleted). Once a stack variable is freed, that region of memory becomes available for other stack variables.

The advantage of using the stack to store variables, is that memory is managed for you. You don't have to allocate memory by hand, or free it once you don't need it any more. What's more, because the CPU organizes stack memory so efficiently, reading from and writing to stack variables is very fast.

A key to understanding the stack is the notion that when a function exits, all of its variables are popped off of the stack (and hence lost forever). Thus stack variables are local in nature. This is related to a concept we saw earlier known as variable scope, or local vs global variables. A common bug in C programming is attempting to access a variable that was created on the stack inside some function, from a place in your program outside of that function (i.e. after that function has exited).

Another feature of the stack to keep in mind, is that there is a limit (varies with OS) on the size of variables that can be store on the stack. This is not the case for variables allocated on the heap.

  • To summarize the stack:

the stack grows and shrinks as functions push and pop local variables

there is no need to manage the memory yourself, variables are allocated and freed automatically

the stack has size limits

stack variables only exist while the function that created them, is running

  • The Heap

The heap is a region of your computer's memory that is not managed automatically for you, and is not as tightly managed by the CPU. It is a more free-floating region of memory (and is larger). To allocate memory on the heap, you must use malloc() or calloc(), which are built-in C functions. Once you have allocated memory on the heap, you are responsible for using free() to deallocate that memory once you don't need it any more. If you fail to do this, your program will have what is known as a memory leak. That is, memory on the heap will still be set aside (and won't be available to other processes). As we will see in the debugging section, there is a tool called valgrind that can help you detect memory leaks.

Unlike the stack, the heap does not have size restrictions on variable size (apart from the obvious physical limitations of your computer). Heap memory is slightly slower to be read from and written to, because one has to use pointers to access memory on the heap. We will talk about pointers shortly.

Unlike the stack, variables created on the heap are accessible by any function, anywhere in your program. Heap variables are essentially global in scope.

© 著作权归作者所有

共有 人打赏支持
上一篇: git log1
下一篇: vimrc
SVD

SVD

粉丝 34
博文 207
码字总数 102940
作品 0
海淀
私信 提问
C# vs C++之二:GC vs RAII

C# vs C++之二:GC vs RAII 资源管理 C中资源管理极为繁琐易错,大多复杂C系统都面临内存泄露、悬挂指针等问题 一方面由底层语言特点决定;另一方面也由于C语言特性相对较少,严重依赖程序员...

ddatsh
2011/06/28
1K
6
彻底超越MFC----诺基亚的开源GUI库:Qt

在Visual Studio 2003/2005/2008下开发Windows图形界面程序,程序员一直做着抉择:选择.net平台,则意味着需要XP用户安装.net Framework, 而且自己不能手工控制某些代码的优化;选择原生C++...

红薯
2010/05/17
4.3K
8
浅谈MFC内存泄露检测及内存越界访问保护机制

本文所有代码均在VC2008下编译、调试。如果您使用的编译器不同,结果可能会有差别,但本文讲述的原理对于大部分编译器应该是相似的。对于本文的标题,实在不知道用什么表示更恰当,因为本文不...

songchang
2012/09/28
0
0
智能指针的设计

智能指针是c++中一个很重要的概念,其实吧,如果c++设计得足够好,智能指针本不应该出现的,c++标准库的智能指针主要解决了两个问题,一个问题是内存释放问题,另一个问题是指针复用问题,也...

晨曦之光
2012/04/10
129
0
c语言基础学习11_项目实战:IDE(集成开发环境)

============================================================================= ============================================================================= 涉及到的知识点有: 一......

黑泽明军
2018/01/29
0
0

没有更多内容

加载失败,请刷新页面

加载更多

HIVE 常见的内置函数

文章目录 1 关系运算 1.1 1、等值比较: = 1.2 2、不等值比较: 1.3 3、小于比较: < 1.4 4、小于等于比较: <= 1.5 5、大于比较: > 1.6 6、大于等于比较: >= 1.7 7、空值判断: IS NULL 1.8 8、非...

瑞查德-Jack
22分钟前
1
0
JVM参数介绍

参数说明 -Xmx3550m:设置JVM最大堆内存为3550M。 -Xms3550m:设置JVM初始堆内存为3550M。此值可以设置与-Xmx相同,以避免每次垃圾回收完成后JVM重新分配内存。 -Xss128k:设置每个线程的栈大...

嘴角轻扬30
28分钟前
3
0
贵州偏僻五线小城,竟冒出一家流水过10亿的互联网公司

“可账上多出来的这一个亿干嘛呢? 投资人万万没想到,杨鹏把这些钱用来买理财产品,一年有四五百万收入。” 这个逗死我了。。 贵州偏僻五线小城,竟冒出一家流水过10亿的互联网公司

火云
28分钟前
1
0
浅谈跨平台框架 Flutter 的优势与结构

作者:个推iOS工程师 伊泽瑞尔 一、背景 目前,移动开发技术主要分为原生开发和跨平台开发两种。其中,原生应用是指在某个特定的移动平台上,使用平台所支持的开发工具和语言,直接调用系统提...

个推
29分钟前
2
0
git 不能访问github 升级ciper

fatal: unable to access  Peer reports incompatible or unsupported protocol version.sudo yum update -y nss curl libcurl...

shengjuntu
33分钟前
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部