C + + Memory allocation Method--Summary

Source: Internet
Author: User

1 How to allocate memory

There are three ways to allocate memory:

    1. Allocate from a static storage area. Memory is allocated when the program is compiled, and the memory is present throughout the program's run, such as global variables, static variables, and so on.
    2. Allocated on the stack. During function execution, the storage units of function parameters, local variables within functions are placed on the stack and are automatically freed from the stack after the function call ends.
    3. Allocation from heap (heap) or free storage space, also called dynamic memory allocation. Use malloc () or new to request memory while the program is running, and free () or delete to release memory.

The general principle is that you should not use dynamic storage if you are using stacks and static storage to meet your application needs. Because the dynamic allocation of memory on the heap requires a lot of extra overhead.

2 common memory errors and their countermeasures
    1. The memory allocation did not use it successfully--check if the pointer is null before using memory.
    2. The memory allocation succeeds, but it has not yet been initialized-to establish the initial consciousness.
    3. The memory allocation succeeds and initializes, but the operation crosses the memory boundary.
    4. Forget to release memory or only partially release memory, causing a memory leak. In addition, the application and release of dynamic memory must match.
    5. Freed up memory and continues to use it.
      • After using free () or delete to release memory, the pointer is not set to NULL, resulting in a "wild pointer".
      • The function return returns a pointer or reference to the stack memory because it is automatically destroyed at the end of the function.
      • Release the same piece of memory multiple times.
3 pointer parameter pass memory

If the parameter of the function is a pointer, do not use it to request a piece of memory. Because the compiler always makes a temporary copy of the function's arguments, the copy of pointer p _p the same value, so it points to the same piece of memory. However, if you use _p to request memory, the memory that P points to does not change at all, but it causes a memory leak after the function ends.

4 free and delete with pointers

Free () and delete simply release the memory that the pointer points to, and do not delete the pointer itself, and in most cases the address that the P points to remains the "wild pointer".

    • When the pointer dies, it does not mean the contents of the pointer are extinct.
    • Memory being freed does not indicate that the pointer is extinct or becomes null.

The "Wild Pointer" has the following causes

    • There is no initialization of pointer variables.
    • After the pointer is free () or delete, it is not set to null.
    • The pointer goes beyond the scope of the variable
5 Malloc/free and New/delete

malloc () and free () are standard library functions of the c++/c language, and New/delete are C + + operators that can dynamically request and release memory.

For objects that are non-intrinsic data types (such as Adt/udt), using malloc () and free () does not satisfy the requirements: object creation automatically calls the constructor, object destruction automatically calls the destructor. Because malloc () and free () are library functions that are not operators and are not within compiler control permissions, the C + + language uses New/delete.

6 Malloc/free Use points

The function malloc prototype is as follows:

void *malloc (size_t size);

For example, to request memory for an integer array of length n:

int *p = (int *) malloc (sizeof (int) * n);

    • The type of the malloc () function return value is void *, so the type conversion is explicitly performed on the call to malloc.
    • malloc () Only cares about the total number of words in memory, does not know what type of memory to apply, and uses the sizeof operator to calculate the size of the type.

The prototype of the function free is as follows:

void free (void * memblock);

7 new 3 Ways to use

New is available in 3 ways: plain New, nothrow new, placement new.

    • Plain NEW: Normal new, throws the standard exception std::bad_alloc--form after failure: new
    • Nothrow NEW: Does not throw an exception after a failure, and checks whether the return value is null--form as in the past: New (Nothrow)
    • Placement NEW: Allows the object or array to be reconstructed on a piece of memory that has been allocated successfully-form: new (P)
8 New/delete Use points

The new built-in sizeof, type conversion, and type safety checks are much simpler than using malloc, for example.

int*p = (int*)malloc(sizeof(int) *n);int*p =New int[N];obj*o =NewOBJ;//constructing an object using the default constructorOBJ *o =NewOBJ (1);//constructing an object using the initial value 1OBJ *o =Newobj[ -];//If you create an array of objects with new, you can only use the default constructorDeleteP//releasing an objectDelete[]o;//frees an array of objects
    • Regardless of type, new/delete and new[]/delete[] must be used correctly
    • Multiple delete of a pointer that is not equal to NULL causes a run-time error.

Finish

C + + Memory allocation Method--Summary

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.