- 浏览: 99441 次
-
文章分类
最新评论
C++ LANGUAGE TUTORIALS : ARRAYS & Dynamic Memory
Dynamic Memory
Until now, in all our programs, we have only had as much memory available as we declared for our variables, having the size of all of them to be determined in the source code, before the execution of the program. But, what if we need a variable amount of memory that can only be determined during runtime? For example, in the case that we need some user input to determine the necessary amount of memory space.The answer is dynamic memory, for which C++ integrates the operators new and delete.
Operators new and new[]
In order to request dynamic memory we use the operator new. new 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 form is:pointer = new type
pointer = new type [number_of_elements]
The first expression is used to allocate memory to contain one single element of type type. The second one is used to assign a block (an array) of elements of type type, where number_of_elements is an integer value representing the amount of these. For example:
|
|
In this case, the system dynamically assigns space for five elements of type int and returns a pointer to the first element of the sequence, which is assigned to bobby. Therefore, now, bobby points to a valid block of memory with space for five elements of type int.

The first element pointed by bobby can be accessed either with the expression bobby[0] or the expression *bobby. Both are equivalent as has been explained in the section about pointers. The second element can be accessed either with bobby[1] or *(bobby+1) and so on...
You could be wondering the difference between declaring a normal array and assigning dynamic memory to a pointer, as we have just done. The most important difference is that the size of an array has to be a constant value, which limits its size to what we decide at the moment of designing the program, before its execution, whereas the dynamic memory allocation allows us to assign memory during the execution of the program (runtime) using any variable or constant value as its 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, it is important to have some mechanism to check if our request to allocate memory was successful or not.
C++ provides two standard methods 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 default method used by new, and is the one used in a declaration like:
|
|
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.
This method can be specified by using a special object called nothrow, declared in header <new>, as argument for new:
|
|
In this case, if the allocation of this block of memory failed, the failure could be detected by checking if bobby took a null pointer value:
|
|
This nothrow method requires more work than the exception method, since the value returned has to be checked after each and every memory allocation, but I will use it in our examples due to its simplicity. Anyway this method can become tedious for larger projects, where the exception method is generally preferred. The exception method will be explained in detail later in this tutorial.
Operators delete and delete[]
Since the necessity of dynamic memory is usually limited to specific moments within a program, once it is no longer needed it should be freed so that the memory becomes available again for other requests of dynamic memory. This is the purpose of the operator delete, whose format is:
|
|
The first expression should be used to delete memory allocated for a single element, and the second one for memory allocated for arrays of elements.
The value passed as argument to delete must be either a pointer to a memory block previously allocated with new, or a null pointer (in the case of a null pointer, delete produces no effect).
|
|
How many numbers would you like to type? 5 Enter number : 75 Enter number : 436 Enter number : 1067 Enter number : 8 Enter number : 32 You have entered: 75, 436, 1067, 8, 32, |
Notice how the value within brackets in the new statement is a variable value entered by the user (i), not a constant value:
|
|
But the user could have entered a value for i so big that our system could not handle 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). Remember that in the case that we tried to allocate the memory without specifying the nothrow parameter in the new expression, an exception would be thrown, which if it's not handled terminates the program.
It is a good practice to always check if a dynamic memory block was successfully allocated. Therefore, if you use the nothrow method, you should always check the value of the pointer returned. Otherwise, use the exception method, even if you do not handle the exception. This way, the program will terminate at that point without causing the unexpected results of continuing executing a code that assumes a block of memory to have been allocated when in fact it has not.
Dynamic memory in ANSI-C
Operators new and delete are exclusive of C++. They are not available in the C language. But using pure C language and its library, dynamic memory can also be used through the functions
malloc,
calloc, realloc and
free, which are also available in C++ including the <cstdlib> header file (see
cstdlib for more info).
The memory blocks allocated by these functions are not necessarily compatible with those returned by new, so each one should be manipulated with its own set of functions or operators.
malloc
void* malloc (size_t size);
Allocates a block of size bytes of memory, returning a pointer to the beginning of the block.
The content of the newly allocated block of memory is not initialized, remaining with indeterminate values.
If size is zero, the return value depends on the particular library implementation (it may or may not be a
null pointer), but the returned pointer shall not be dereferenced.
Parameters
size_t is an unsigned integral type.
Return Value
On success, a pointer to the memory block allocated by the function.
The type of this pointer is always void*
, which can be cast to the desired type of data pointer in order to be dereferenceable.
If the function failed to allocate the requested block of memory, a null pointer is returned.
Example
|
|
This program generates a string of the length specified by the user and fills it with alphabetic characters. The possible length of this string is only limited by the amount of memory available to
malloc
Data races
Only the storage referenced by the returned pointer is modified. No other storage locations are accessed by the call.
If the function reuses the same unit of storage released by a deallocation function (such as
free or realloc), the functions are synchronized in such a way that the deallocation happens entirely before the next allocation.
Exceptions (C++)
No-throw guarantee: this function never throws exceptions.
calloc
void* calloc (size_t num, size_t size);
Allocates a block of memory for an array of num elements, each of them
size bytes long, and initializes all its bits to zero.
The effective result is the allocation of a zero-initialized memory block of
(num*size)
bytes.
If size is zero, the return value depends on the particular library implementation (it may or may not be a
null pointer), but the returned pointer shall not be dereferenced.
Parameters
size_t is an unsigned integral type.
Return Value
On success, a pointer to the memory block allocated by the function.
The type of this pointer is always void*
, which can be cast to the desired type of data pointer in order to be dereferenceable.
If the function failed to allocate the requested block of memory, a null pointer is returned.
Example
|
|
This program simply stores numbers and then prints them out. But the number of items it stores can be adapted each time the program is executed because it allocates the needed memory during runtime.
free
void free (void* ptr);
A block of memory previously allocated by a call to malloc,
calloc or realloc is deallocated, making it available again for further allocations.
If ptr does not point to a block of memory allocated with the above functions, it causes
undefined behavior.
If ptr is a null pointer, the function does nothing.
Notice that this function does not change the value of ptr itself, hence it still points to the same (now invalid) location.
Parameters
Return Value
none
Example
|
|
This program has no output. It just demonstrates some ways to allocate and free dynamic memory using the
C stdlib functions.
相关推荐
ARKit by Tutorials: Building Augmented Reality Apps in Swift 4.2, 2nd Edition by Chris Language-2019(pdf)-分卷4-共5分卷 解压密码:19990323 ARKit by Tutorials: Building Augmented Reality Apps in ...
ARKit by Tutorials: Building Augmented Reality Apps in Swift 4.2, 2nd Edition by Chris Language-2019(pdf)-分卷3-共5分卷 解压密码:19990323 ARKit by Tutorials: Building Augmented Reality Apps in ...
ISO C++ Standard:官方 C++ 标准文档,提供了详细的开发指南和 API 文档。...C/C++ Tutorials:官方 C/C++ 教程,提供了详细的开发指南和 API 文档。 书籍资源 "The C Programming Language":一个
ARKit by Tutorials: Building Augmented Reality Apps in Swift 4.2, 2nd Edition by Chris Language-2019(pdf)-分卷2-共5分卷 解压密码:19990323 ARKit by Tutorials: Building Augmented Reality Apps in ...
ARKit by Tutorials: Building Augmented Reality Apps in Swift 4.2, 2nd Edition by Chris Language-2019(pdf)-分卷1-共5分卷 解压密码:19990323 ARKit by Tutorials: Building Augmented Reality Apps in ...
ARKit by Tutorials: Building Augmented Reality Apps in Swift 4.2, 2nd Edition by Chris Language-2019(pdf)-分卷0-共5分卷 解压密码:19990323 ARKit by Tutorials: Building Augmented Reality Apps in ...
ARKit by Tutorials: Building Augmented Reality Apps in Swift 4.2, 2nd Edition by Chris Language English | 2019 | ISBN: 1942878711 | 496 Pages | True PDF, CODE | 1623 MB Learn ARKit, Apple’s New ...
Metal by Tutorials: Beginning game engine development with Metal by Caroline Begbie English | 2019 | ISBN: 1942878544 | 659 Pages | True PDF, EPUB, CODE | 790 MB Build your own low-level game engine ...
Metal by Tutorials: Beginning game engine development with Metal by Caroline Begbie English | 2019 | ISBN: 1942878544 | 659 Pages | True PDF, EPUB, CODE | 790 MB Build your own low-level game engine ...
《iOS Animations by Tutorials v4.0 && Source Code》是一本专注于iOS动画技术的教程,结合了最新的动画技术和源代码,旨在帮助开发者提升在iOS平台上创建动态、引人入胜用户体验的能力。这本书覆盖了从基础到高级...
Metal by Tutorials: Beginning game engine development with Metal by Caroline Begbie English | 2019 | ISBN: 1942878544 | 659 Pages | True PDF, EPUB, CODE | 790 MB Build your own low-level game engine ...
Machine Learning by Tutorials: Beginning machine learning for Apple and iOS by Matthijs Hollemans-- May 31, 2019 Machine Learning by Tutorials: Beginning machine learning for Apple and iOS by ...
Machine Learning by Tutorials: Beginning machine learning for Apple and iOS by Matthijs Hollemans-- May 31, 2019 Machine Learning by Tutorials: Beginning machine learning for Apple and iOS by ...
Machine Learning by Tutorials: Beginning machine learning for Apple and iOS by Matthijs Hollemans-- May 31, 2019 Machine Learning by Tutorials: Beginning machine learning for Apple and iOS by ...
ARKit by Tutorials: Building Augmented Reality Apps in Swift 4.2, 2nd Edition by Chris Language English | 2019 | ISBN: 1942878711 | 496 Pages | True PDF, CODE | 1623 MB Learn ARKit, Apple’s New ...
ARKit by Tutorials: Building Augmented Reality Apps in Swift 4.2, 2nd Edition by Chris Language English | 2019 | ISBN: 1942878711 | 496 Pages | True PDF, CODE | 1623 MB Learn ARKit, Apple’s New ...
ARKit by Tutorials: Building Augmented Reality Apps in Swift 4.2, 2nd Edition by Chris Language English | 2019 | ISBN: 1942878711 | 496 Pages | True PDF, CODE | 1623 MB Learn ARKit, Apple’s New ...
ARKit by Tutorials: Building Augmented Reality Apps in Swift 4.2, 2nd Edition by Chris Language English | 2019 | ISBN: 1942878711 | 496 Pages | True PDF, CODE | 1623 MB Learn ARKit, Apple’s New ...