C + + dynamic memory allocation __c++

Source: Internet
Author: User

The author introduces: Jiang Xiewei, IT company technical partner, it senior lecturer, CSDN Community experts, invited editors, best-selling authors, published books: "Hands-on teaching you architecture 3D Game Engine" Electronics publishing house and "Unity3d actual combat core technical details" Electronic industry publishing house and so on.

CSDN Video URL: http://edu.csdn.net/lecturer/144

Dynamic memory allocation in C/s + + refers to the manual execution of memory allocations by programmers, the allocation of dynamically allocated memory to the heap, and non-static and local variables to acquire memory allocated on the stack. For more information see the previous blog: C program memory layout.

what is an application.
One use of dynamically allocated memory is allocating variable size memory, except for variable-length arrays, where the compiler is not able to allocate memory.
The most important use is to provide flexibility for programmers whenever we need to, and we no longer need, we can allocate and release memory at any time, in many cases, this flexibility is helpful, this example is the link list, tree and so on.

is different from the memory assigned to the normal variable.
For general variables such as "int a", "char str [10]", memory is automatically allocated and released. For dynamically allocated memory, such as "int * p = new int [10]", it is the responsibility of the programmer to free memory when it is no longer needed. If the programmer does not release memory, it causes a memory leak (memory is not released until the program terminates).

What is a memory leak and how to avoid it.

Memory leaks occur when programmers create memory in the heap and forget to delete memory, which is a particularly serious problem for the program. The following is a memory leak code:

/* Function with memory leak */
#include <stdlib.h>
 
void f ()
{
   int *ptr = (int *) malloc (sizeof (int) );
 
   /* Do some work * * return
 
   without freeing ptr*/
}
To avoid memory leaks, the memory allocated to the heap should be freed when it is no longer needed.

#include <stdlib.h>;
 
void f ()
{
   int *ptr = (int *) malloc (sizeof (int));
 
   /* Do some work * * free
 
   (PTR);
   return;
}
How to allocate/free memory in C + +.
C uses the malloc () and calloc () functions to dynamically allocate memory at run time and use the free () function to release dynamically allocated memory. C + + supports these features, and there are two operators new and delete to perform the task of allocating and freeing memory.
This article is about the operators of new and delete. new operator

The new operator represents a memory allocation request on the heap. If enough memory is available, the new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.

Syntax for using the new operator: the memory to allocate any data type, the syntax is:

pointer-variable = new Data-type;

Here, the pointer variable is a pointer to a data type type that can be any built-in data type, including an array or any user-defined data type, including structs and classes.

Pointer initialized with NULL
//Then request memory for the variable
int *p = NULL; 
p = new int;   

            or

//Combine declaration of Pointer 
//and their assignment
Initialize memory, we can use new to initialize memory

pointer-variable = new Data-type (value);
Example:
int *p = new int (a);
float *q = new float (75.25);

Allocating memory block: The new operator is also used to allocate memory blocks (arrays) of data types.

pointer-variable = new Data-type[size];

where size (a variable) specifies the number of elements in the array.

int *p = new INT[10]

Dynamically allocates 10 integer memory for type int and returns a pointer to the first element of the sequence, assigned to P (pointer), p [0] refers to the first element, p [1] is the second element, and so on.

Array declaration with the new operator

The most important difference between declaring an array and using the new memory block allocation is that the array is freed by the compiler (if the array is local, it is released when the function returns or completes). However, dynamically allocated arrays are always kept there until they are terminated by a programmer or program.

What to do if there is not enough memory at run time.
If there is not enough memory in the heap to allocate, the new request indicates a failure by throwing an exception of type std:: Bad_alloc, and the new operator returns a pointer. Therefore, it might be a good idea to check for new pointer variables before using the program.

int *p = new int;
if (!p)
{
   cout << "Memory allocation failed\n";
}
Delete operator

Since programmers are responsible for releasing dynamically allocated memory, the C + + language is used to provide programmers with the delete operator.

Delete pointer-variable;
Here, the pointer variable is a pointer to the data object created by new.
Example:

  Delete p;
  Delete q;

To release the dynamically allocated array that is pointed to by the pointer variable, use the following form of delete:

Release blocks of memory 
//pointed by pointer-variable
delete[] pointer-variable;  

Example:
   //It'll free the entire array
   //pointed by P.
   Delete[] p;

The complete case code looks like this:

#include <iostream> using namespace std;
 
    int main () {//pointer initialization to NULL int* p = null;
    Request memory for the variable//using new operator P = new int;
    if (!p) cout << "Allocation of memory failed\n";
        else {//Store value at allocated address *p = 29;
    cout << "Value of P:" << *p << Endl;
 
    //Request block of memory//using new operator float *r = new float (75.25);
 
    cout << "Value of R:" << *r << Endl;
    Request block of memory of size n int n = 5;
 
    int *q = new Int[n];
    if (!p) cout << "Allocation of memory failed\n";
 
        else {for (int i = 0; i < n; i++) q[i] = i+1;
        cout << "Value store in block of memory:";
    for (int i = 0; i < n; i++) cout << q[i] << ""; }//Freed the allocated memory delete p;
    Delete R;
 
    Freed the block of allocated memory delete[] Q;
return 0; }
Output results:

Value of p:29
value of r:75.25


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.