In the programs seen in previous chapters, all memory needs were determined before program execution by defining the variables needed. But there may be cases where the memory needs of a program can only be determined during runtime. For example, when the memory needed depends on user input. On these cases, programs need to dynamically allocate memory, for which the C++ language integrates the operators new and delete.

Operators new and new[]

Dynamic memory is allocated using operator newnew is followed by a data type specifier and, if a sequence of more than one element is required, the number of these within brackets []. It returns a pointer to the beginning of the new block of memory allocated. Its syntax is: 

pointer = new type //allocate memory to contain one single element of type type pointer = new type [number_of_elements]    //allocate a block (an array) of elements of type type

 

The first expression is used to allocate memory to contain one single element of type type. The second one is used to allocate a block (an array) of elements of type type, where number_of_elements is an integer value representing the amount of these. For example:

int * foo; foo = new int [];

 

In this case, the system dynamically allocates space for five elements of type int and returns a pointer to the first element of the sequence, which is assigned to foo (a pointer). Therefore, foo now points to a valid block of memory with space for five elements of type int.

 

 

           first element          second element
foo[] 或者 *foo

 

foo[] 或者 *(foo+)

 

the pointed to by foo

Here, foo is a pointer, and thus, the first element pointed to by foo can be accessed either with the expression foo[0] or the expression *foo (both are equivalent). The second element can be accessed either with foo[1] or *(foo+1), and so on...

 

 

  • difference between declaring a normal array and allocating dynamic memory for a block of memory using new


 The most important difference is that the size of a regular array needs to be a constant expression, and thus its size has to be determined at the moment of designing the program, before it is run, whereas the dynamic memory allocation performed by new allows to assign memory during runtime using any variable value as size.

The dynamic memory requested by our program is allocated by the system from the memory heap. However, computer memory is a limited resource, and it can be exhausted. Therefore, there are no guarantees that all requests to allocate memory using operator new are going to be granted by the system. 

C++ provides two standard mechanisms to check if the allocation was successful:

One is by handling exceptions. Using this method, an exception of type bad_alloc is thrown when the allocation fails. Exceptions are a powerful C++ feature explained later in these tutorials. But for now, you should know that if this exception is thrown and it is not handled by a specific handler, the program execution is terminated.

This exception method is the method used by default by new, and is the one used in a declaration like:

foo = new int [];  // if allocation fails, an exception is thrown 

 

The other method is known as nothrow, and what happens when it is used is that when a memory allocation fails, instead of throwing a bad_alloc exception or terminating the program, the pointer returned by new is a null pointer, and the program continues its execution normally.

This method can be specified by using a special object called nothrow, declared in header <new>, as argument for new:

 
foo = new (nothrow) int [5]; 

In this case, if the allocation of this block of memory fails, the failure can be detected by checking if foo is a null pointer:

1
2
3
4
5
int * foo; foo = new (nothrow) int [5]; if (foo == nullptr) { // error assigning memory. Take measures. }

This nothrow method is likely to produce less efficient code than exceptions, since it implies explicitly checking the pointer value returned after each and every allocation. Therefore, the exception mechanism is generally preferred, at least for critical allocations. Still, most of the coming examples will use the nothrow mechanism due to its simplicity.

Operators delete and delete[]

In most cases, memory allocated dynamically is only needed during specific periods of time within a program; once it is no longer needed, it can be freed so that the memory becomes available again for other requests of dynamic memory. This is the purpose of operator delete, whose syntax is:

delete pointer; delete[] pointer;

 

The first statement releases the memory of a single element allocated using new, and the second one releases the memory allocated for arrays of elements using new and a size in brackets ([]).

The value passed as argument to delete shall be either a pointer to a memory block previously allocated with new, or a null pointer (in the case of a null pointerdelete produces no effect).

 
// rememb-o-matic
#include <iostream> #include <new>
using namespace std; int main () { int i,n; int * p; cout << "How many numbers would you like to type? "; cin >> i; p= new (nothrow) int[i]; if (p == nullptr) cout << "Error: memory could not be allocated"; else { for (n=; n<i; n++) { cout << "Enter number: "; cin >> p[n]; } cout << "You have entered: "; for (n=; n<i; n++) cout << p[n] << ", "; delete[] p; } return ; }

 

How many numbers would you like to type?  Enter number :  Enter number :  Enter number :  Enter number :  Enter number :  You have entered: , , , , ,

 

Notice how the value within brackets in the new statement is a variable value entered by the user (i), not a constant expression:

 
p= new (nothrow) int[i];

There always exists the possibility that the user introduces a value for i so big that the system cannot allocate enough memory for it. For example, when I tried to give a value of 1 billion to the "How many numbers" question, my system could not allocate that much memory for the program, and I got the text message we prepared for this case (Error: memory could not be allocated).

It is considered good practice for programs to always be able to handle failures to allocate memory, either by checking the pointer value (if nothrow) or by catching the proper exception.

Dynamic memory in C

C++ integrates the operators new and delete for allocating dynamic memory. But these were not available in the C language; instead, it used a library solution, with the functions malloccallocrealloc and free, defined in the header<cstdlib> (known as <stdlib.h> in C). The functions are also available in C++ and can also be used to allocate and deallocate dynamic memory.

Note, though, that the memory blocks allocated by these functions are not necessarily compatible with those returned bynew, so they should not be mixed; each one should be handled with its own set of functions or operators.

 

(转) Dynamic memory的更多相关文章

  1. 论文笔记:Learning Dynamic Memory Networks for Object Tracking

    Learning Dynamic Memory Networks for Object Tracking  ECCV 2018Updated on 2018-08-05 16:36:30 Paper: ...

  2. c++ Dynamic Memory (part 1)

    1. make_shared<T>(args): return a shared_ptr dynamically allocated object of type T. Use args ...

  3. 动态内存分配(Dynamic memory allocation)

    下面的代码片段的输出是什么?为什么? 解析:这是一道动态内存分配(Dynamic memory allocation)题.    尽管不像非嵌入式计算那么常见,嵌入式系统还是有从堆(heap)中动态分 ...

  4. 从五大结构体,带你掌握鸿蒙轻内核动态内存Dynamic Memory

    摘要:本文带领大家一起剖析了鸿蒙轻内核的动态内存模块的源代码,包含动态内存的结构体.动态内存池初始化.动态内存申请.释放等. 本文分享自华为云社区<鸿蒙轻内核M核源码分析系列九 动态内存Dyna ...

  5. c++ Dynamic Memory (part 2)

    Don't use get to initialize or assign another smart pointer. The code that use the return from get c ...

  6. [Paper翻译]Scalable Lock-Free Dynamic Memory Allocation

    原文: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.87.3870&rep=rep1&type=pdf Abstr ...

  7. C++ storage allocation + Dynamic memory allocation + setting limits + initializer list (1)

    1. 对象的空间在括号开始就已经分配,但是构造在定义对象的时候才会实现,若跳过(譬如goto),到括号结束析构会发生错误,编译会通不过. 2.初始化 1 struct X { int i ; floa ...

  8. 基于神经网络的混合计算(DNC)-Hybrid computing using a NN with dynamic external memory

    前言: DNC可以称为NTM的进一步发展,希望先看看这篇译文,关于NTM的译文:人工机器-NTM-Neutral Turing Machine 基于神经网络的混合计算 Hybrid computing ...

  9. (C/C++) Interview in English. - Memory Allocation/Deallocation.

    Q: What is the difference between new/delete and malloc/free? A: Malloc/free do not know about const ...

随机推荐

  1. OpenGL ES 2.0 符点精度

    片元着色器中使用符点相关类型的变量时与顶点着色器中有所不同,在顶点着色器中直接声明使用即可,而在片元着色器中必须指定精度. lowp 低 mediump 中 highp 高 指定整个着色器中符点相关类 ...

  2. HLS(HTTP Live Streaming)协议之m3u8文件生成方式

    HLS(HTTP Live Streaming)是Apple的动态码率自适应技术.主要用于PC和Apple终端的音视频服务.包括一个m3u(8)的索引文件,TS媒体分片文件和key加密串文件. HLS ...

  3. 35个jQuery小技巧(转)

    1. 禁止右键点击$(document).ready(function(){    $(document).bind("contextmenu",function(e){     ...

  4. 如何从数据库(实体提供者)读取安全用户(转自http://wiki.jikexueyuan.com/project/symfony-cookbook/entity-provider.html)

    Symfony 的安全系统可以通过活动目录或开放授权服务器像数据库一样从任何地方加载安全用户.这篇文章将告诉你如何通过一个 Doctrine entity 从数据库加载用户信息. 前言 在开始之前,您 ...

  5. js 非IE火狐插件检测

    js检测代码Html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:// ...

  6. 转载收藏之用 - 微信公众平台开发教程(七):解决用户上下文(Session)问题

    从这篇文章中我们已经了解了微信公众平台消息传递的方式,这种方式有一个先天的缺陷:不同用户的请求都来自同一个微信服务器,这使得常规的Session无法使用(始终面对同一个请求对象,况且还有对方服务器Co ...

  7. Android手机配置gcc,实现手机编译代码

    1.下载gcc.zip 2.把gcc.zip解压存放在/data目录下(也可以是其他目录,看个人习惯) 3.配置gcc环境变量 export GCCHOME=/data/gcc (gcc存放路径) e ...

  8. LibSvm介绍---调用方法及参数介绍

        libsvm是著名的SVM开源组件,目前有JAVA.C/C++,.NET 等多个版本,本人使用的是2.82 libsvm命名空间下主要使用类: svm_model 为模型类,通过训练或加载训练 ...

  9. smarty模板执行原理

    为了实现程序的业务逻辑和内容表现页面的分离从而提高开发速度,php 引入了模板引擎的概念,php 模板引擎里面最流行的可以说是smarty了,smarty因其功能强大而且速度快而被广大php web开 ...

  10. postgresql C/C++ API 接口

    1,postgresql学习uri推荐 http://www.php100.com/manual/PostgreSQL8/ http://www.php100.com/manual/PostgreSQ ...