C + + memory management issues

Source: Internet
Author: User

There are three ways to allocate memory:
(1) allocation from a static storage area. Memory is allocated at the time of program compilation, and the entire running period of the program is present in this block . For example, global variables, static variables.

(2) Create on the stack. When executing a function, the storage unit of the local variable within the function can be created on the stack, which is automatically freed at the end of its execution. Stack Memory points

instruction set built into the processor by the matching operation , the efficiency is high, but the allocated memory capacity is limited.

(3) allocation from the heap, also known as dynamic memory allocation. The program uses malloc or new to apply any amount of memory at run time, and the programmer is responsible for when to use free or

Delete to free up memory. The lifetime of dynamic memory is determined by us and is very flexible to use, but the problem is the most. The application and release of dynamic memory must be paired to prevent memory leaks.

checks if the pointer is NULL before using memory. If the pointer p is an argument to a function, it is checked with an assert (P!=null) at the entrance of the function.

If you are using malloc or new to request memory, you should use if (p==null) or if (p!=null) for error-proof handling.

There is no uniform standard for what the default initial value of memory is, although at some point it is a zero value, we would rather believe It is all credible that it has. So no matter how you create an array,

Do not forget to assign the initial value, even if it is assigned 0 values can not be omitted.

Note that you do not return a pointer or reference to "stack memory" because the memory ends in the function body from when being destruction.

When memory is freed with free or delete, the pointer is set to NULL. In case the "wild pointer" is generated.

The array name corresponds to (instead of pointing to) a piece of memory, and the array name is equivalent to a constant pointer whose address and capacity remain constant over the lifetime, and only the contents of the array can be changed.

Pointers can point to any type of block of memory at any time, and its characteristics are "mutable", so we use pointers to manipulate dynamic memory. Pointers are far more flexible than arrays, but they are also more dangerous.

For the same char string char str[] = "Hellow":

The value of strlen (str) is 6, which is the number of valid characters for this string, not including the 0 for the end string.

The value of sizeof (STR) is 7, which is the number of bytes that this variable occupies in total memory, which of course contains the last 0 to end the string.

for char *p = str; The value of sizeof (p) is the capacity that the int variable occupies in memory. The c++/c language has no way of knowing the memory capacity that the pointer refers to.

Note that when an array is passed as an argument to a function, the array is automatically degraded to a pointer of the same type.

void Func (char a[100])
{
cout<< sizeof (a) << Endl; 4 bytes instead of 100 bytes
}

if the parameter of the function is a pointer, do not expect to use the pointer to apply dynamic memory.

GetMemory (str, 200) does not have the desired memory for STR, and STR is still NULL. (pass by value)

void GetMemory (char *p, int num)
{
p = (char *) malloc (sizeof (char) * num); The system will open a temporary storage area to hold the value p, where p is not the original P pass by value
}

If you have to use pointer parameters to request memory, you should instead use a pointer to pointer.

void GetMemory2 (char **p, int num)
{
*p = (char *) malloc (sizeof (char) * num);
}

char * Test1 (void)
{
Char str[] = "hellow!"; It is emphasized that you should not return a pointer to "stack memory" with a return statement. Because STR is a string, str is created in the stack.
return str;
}

Char *test2 (void)
{
Char *pstr = "hellow!"; /because "hellow!" is a string, it is stored in a static storage area, and PSTR is just a pointer, according to the pass by value, even if PSTR is eliminated in the stack, "Hellow" still exists
return pStr;
}

Free and delete simply release the memory that the pointer refers to, but do not kill the pointer itself. If you do not set the pointer to NULL at this point, the person will mistakenly assume that p is a valid pointer.

If the program is long, we sometimes remember whether P refers to the memory has been released, in the continued use of P , the statement if (P! = NULL) is usually used for error-proof handling.

(1) The pointer dies and does not indicate that the memory it refers to is automatically released.
(2) Memory is freed, does not indicate that the pointer is extinct or is a NULL pointer

There are two main causes of the "wild pointer":
(1) The pointer variable is not initialized. Any pointer variable that has just been created does not automatically become a NULL pointer, it
The default value is random, it will be arbitrary.

(2) The pointer p is not set to NULL after the free or delete, which makes the person mistakenly think P is a valid pointer.

(3) The pointer operation goes beyond the scope of the variable. For example:

void Test (void)
{
A *p;
{
A;
p = &a; Notice the lifetime of a
}
P->func (); P is the "wild pointer"
}

Optical Maloc/free cannot meet the requirements of dynamic objects. Objects are automatically executed when they are created, and the object executes the destructor automatically before it dies. Because
Malloc/free is a library function, not an operator, not within the control of the compiler, and is not able to impose the task of executing constructors and destructors on Malloc/free.

Therefore, the C + + language requires an operator new that can perform dynamic memory allocation and initialization, and an operator delete that can perform cleanup and deallocation work.

Note New/delete is not a library function.

Because C + + programs often have to call C functions, the program can only use Malloc/free to manage dynamic memory. Therefore, C + + does not eliminate malloc/free.

How to run out of memory

If you cannot find a large enough block of memory when you request dynamic memory, malloc and new will return a NULL pointer.
Declared memory request failed. There are typically three ways to handle the "memory exhaustion" issue.

(1) Determine if the pointer is NULL, and if so, terminate the function with the return statement immediately.

(2) Determine if the pointer is NULL, and if so, use Exit (1) to terminate the entire program operation immediately.

(3) Set exception handling functions for new and malloc.

Page 54

C + + memory management issues

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.