C + + dynamic memory allocation

Source: Internet
Author: User
Tags value store

The author introduces: Jiang Xiewei, IT company technology partner, it senior lecturer, CSDN Community expert, guest editor, best-selling author, published book: "Teach You architecture 3D Game engine" electronic industry publishing house and "Unity3d Actual combat core technology detailed" 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 programmer performing memory allocations manually, allocating memory dynamically to the heap, non-static, and local variables to get the memory allocated on the stack. For details, see the previous blog post: C program memory layout.

What is an application?
One use of dynamically allocated memory is to allocate memory of variable size, except for variable-length arrays, where the compiler is unlikely 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 free memory at any time, in many cases, this flexibility is helpful, this example is linked list, tree and so on.

What is the difference between memory assigned to a normal variable?
For general variables such as "int a", "char str [10]", memory is automatically allocated and freed. For dynamically allocated memory, such as "int * p = new int [10]", it is the programmer's responsibility to free up 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?

A memory leak occurs when a programmer creates memory in the heap and forgets to delete memory, which is a particularly serious problem for a program. The following is the code for the memory leak:

[CPP]View PlainCopy
    1. /* function with memory  leak */  
    2. #include  <stdlib.h>   
    3.    
    4. void f ()   
    5. {&NBSP;&NBSP;
    6.    int *ptr  =  (int *)  malloc (sizeof ( int));   
    7. &NBSP;&NBSP;&NBSP;
    8.    < span class= "comment" >/* do some work */  
    9.     
    10.    return; /* return  without freeing ptr*/  
    11. }&NBSP;&NBSP;

To avoid a memory leak, the memory allocated to the heap should be freed when it is no longer needed.

[CPP]View PlainCopy
    1. #include  <stdlib.h>;   
    2.    
    3. void f ()   
    4. {  
    5.    int *ptr  =  (int *)  malloc (sizeof ( int));   
    6.    
    7.    < span class= "comment" >/* do some work */  
    8.    
    9. Li class= "alt" >   free (PTR);   
    10.    return;   
    11. }&NBSP;&NBSP;

How do I 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 new and delete operators.

New operator

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

Use the syntax of the new operator: to allocate memory of any data type, the syntax is:

pointer-variable = new Data-type;

Here, a pointer variable is a pointer to a data type type, which 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 variableint *p = NULL; p = new int;               

Initialize memory, we can initialize memory with new

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

Allocating memory blocks: 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 integers of 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] refers to the second element, and so on.

Array declarations 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 released by the programmer or program termination.

What if run-time memory is low?
If there is not enough memory in the heap available for allocation, 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 the programmer is responsible for releasing the dynamically allocated memory, the C + + language is used to provide the delete operator for the programmer.

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 block of memory//pointed by pointer-variabledelete[] pointer-variable;  Example:   //It would free the entire array   //pointed by P.   Delete[] p;

The complete case code is as follows:

[CPP]View PlainCopy
  1. #include <iostream>
  2. Using namespace std;
  3. int main ()
  4. {
  5. //Pointer initialization to NULL
  6. int* p = NULL;
  7. //Request memory for the variable
  8. //Using new operator
  9. p = new int;
  10. if (!p)
  11. cout << "Allocation of memory failed\n";
  12. Else
  13. {
  14. //Store value at allocated address
  15. *p = 29;
  16. cout << "Value of P:" << *p << Endl;
  17. }
  18. //Request block of memory
  19. //Using new operator
  20. float *r = new float (75.25);
  21. cout << "Value of R:" << *r << Endl;
  22. //Request block of memory of size n
  23. int n = 5;
  24. int *q = new int[n];
  25. if (!p)
  26. cout << "Allocation of memory failed\n";
  27. Else
  28. {
  29. For (int i = 0; i < n; i++)
  30. Q[i] = i+1;
  31. cout << "Value store in block of memory:";
  32. For (int i = 0; i < n; i++)
  33. cout << Q[i] << "";
  34. }
  35. //Freed the allocated memory
  36. Delete p;
  37. Delete R;
  38. //freed the block of allocated memory
  39. delete[] Q;
  40. return 0;
  41. }

Output Result:

http://www.woaipu.com/shops/zuzhuan/61406
http://nanning.xjwy.cn/f/bencandy.php?fid=43&id=117777
http://nanning.xjwy.cn/f/bencandy.php?fid=43&id=117890
http://nanning.xjwy.cn/f/bencandy.php?fid=43&id=117994
http://nanning.xjwy.cn/f/bencandy.php?fid=43&id=118376



C + + dynamic memory allocation

Related Article

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.