C ++ Memory Management (1)

Source: Internet
Author: User


1. Memory Allocation Method
(1) distribution from the static storage area. For example, static and global variables are used. The data in the static storage area has been allocated when the program is compiled. It exists during the running of the program and will be released only after the program is released.
(2) stack allocation. The local variables in the function are allocated on the stack, and the storage space is released when the function order is reached;
(3) allocate on the stack. Programmers apply for and release memory (new/delete malloc/free) based on their own needs)
2. Some errors often occur during memory allocation.
(1) The memory is used when it is not allocated successfully. For example, if the memory does not have enough space to spare, when the memory allocation (new/malloc) fails, NULL is returned. You can use assert (p! = NULL) or if statement.
(2) If the memory is allocated successfully, but it is not initialized, It is referenced. Int * p = newint (10); // forget to initialize
(3) memory allocation is successful, but out-of-bounds operations are performed. When the array tag is used, "more than 1" and "less than 1" may appear"
(4) forget to release the memory, causing memory leakage.
(5) continue to use the memory after it is released (delete)
3. pointers and Arrays
(1) modification content
Char a [] = "hello ";
A [0] = 'X ';
Cout <a <endl;
Char * p = "world"; // here p is defined to point to a constant string
P [0] = 'X'; // error. The constant string value cannot be changed.
Cout <endl;
(2) When an array is passed as a function parameter, the array will automatically degrade to a pointer of the same type.
Void printLen (char a [1, 100])
{
Cout <sizeof (a) <endl; // 4 instead of 100 is output here
}
(3) pointer parameter transfer memory
If a function parameter is a pointer, do not use this pointer to request dynamic memory. For example:
Void getMem (char * p, int len)
{
P = (char *) malloc (sizeof (char) * len );
}
Void test (void)
{
Char * str = NULL;
GetMem (str, 1100); // after execution, str is still NULL
Strcopy (str, "hello"); // The running error is caused by str = NULL.
}
 
The preceding running error is because, in the function, it is important to make a temporary copy for each parameter. In getMem, the copy of the pointer parameter p is _ p, in the compiler, it will make _ p = p. In this way, the content pointed to by _ p is modified in the function body, which is the root cause of the pointer as an output parameter. However, in the getMem function, the temporary replicas _ p applied for a new memory space and changed the space pointed to by _ p, then, when _ p points to the content, the content that p points to is not changed. In addition, the free function is not used to release the memory. Therefore, a piece of memory is leaked every time getMem is executed.

Solution: by pointing to a pointer or returning a pointer
(1) pointer to pointer
Void getMem1 (char ** p, int num)
{
* P = (char *) malloc (sizeof (char) * num );
}
Void test1 (void)
{
Char * str = NULL;
GetMem1 (& str, 100); // note that & str
Strcpy (str, "hello ");
Cout <str <endl;
Free (str); // do not forget to release the memory
}
 
(2) return a pointer using return
Although it is better to use the return value of a function to dynamically pass the memory, sometimes programmers may mistakenly return the results returned by the return Statement. It is emphasized that the return statement should not be used to return the pointer to the stack memory, because the function will be released when it ends, the next time you access the memory space, the stored data may not be the original data. For example:
# Include "stdafx. h"
# Include <iostream>
Using namespace std;
 
Char * getStr (void)
{
Char str1 [] = "hello world"; // the data is stored on the stack. The space will be released after the function order.
// Because the returned str points to this address, when this address is used again later
// The str space has been allocated to other variables.
// Error.
Cout <"str1 [] address" <& str1 <endl;
Returnstr1; // the compiler will warn you that the address returned by VC6.0 is 0x0012FE90.
}
 
Void test ()
{
Char * str2 = NULL;
Str2 = getStr (); // str2 = 0x0012FEF0
Cout <"str2 address" <& str2 <endl;
Cout <str2 <endl; // The output is not "hello world", but a messy string, because it does not know what is stored in str2.
}
 
Void main (void)
{
Test ();
}
Note: here we can modify the variable definitions in the following function:
Char * getStr (void)
{
Char str1 [] = "hello world ";
}
The variables in this function can be defined in the static storage area to output "hello world"
For example, static char str1 [] = "hello world"; or char * p = "hello world"; // note that the second method defines a character constant.
Author: qingtingchen1987

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.