c++--Memory Usage

Source: Internet
Author: User
Tags strcmp


Memory allocation Method:
(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 units of local variables within the function can be created on the stack, which are automatically freed when the function is executed at the end. The stack memory allocation operation is built into the processor's instruction set and is highly efficient, but allocates limited memory capacity.
(3) Allocation from the heap, also known as dynamic memory allocation. When the program is running, it uses malloc or new to request any amount of memory, and the programmer is responsible for freeing the memory with free or delete. The lifetime of dynamic memory is determined by us and is very flexible to use, but the problem is the most.

Common memory errors and their countermeasures:
A memory error is a very troublesome thing to happen. These errors are not automatically discovered by the compiler and are usually captured when the program is running. And most of these errors are not obvious symptoms, and the hidden, increased the difficulty of error. Sometimes the user angrily to find you, the program did not have any problems, you go, wrong and attack. Common memory errors and their countermeasures are as follows:

* Memory allocation was unsuccessful, but it was used
Novice programmers often make this mistake because they are unaware that the memory allocation will not succeed. A common workaround is to check 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.

* Memory allocation succeeds, but is not initialized to reference it
There are two main causes of this error: one is the idea of no initialization, and the other is to mistakenly assume that the default initial value of the memory is all zero, resulting in a reference to the initial error (for example, an array). There is no uniform standard for what the default initial value of memory is, although sometimes it is a zero value and we would rather believe it to be credible. So no matter how to create an array, do not forget to assign the initial value, even if it is assigned 0 values can not be omitted, do not bother.

* The memory allocation succeeds and has been initialized, but the operation crosses the memory boundary
For example, the use of arrays often occurs when the subscript "more 1" or "less 1" operation. Especially in a For loop statement, the number of loops can be easily mistaken, resulting in array operations being out of bounds.

* Forgot to release memory, causing memory leak
The function that contains this error loses one piece of memory each time it is called. At first, the system has plenty of memory and you can't see the error. One time the program suddenly died, the system appears prompt: memory exhaustion.
Dynamic memory application and release must be paired, the program malloc and free use must be the same number, otherwise there must be errors (new/delete).

* Freed up memory but continued to use it
There are three types of cases:
(1) The object call relationship in the program is too complex, it is difficult to know whether an object has freed the memory, at this time should redesign the data structure, fundamentally solve the chaos of object management.
(2) The return statement of the function is incorrectly written, and be careful not to return a pointer or reference to "stack memory" because the memory is automatically destroyed at the end of the function body.
(3) After releasing memory with free or delete, the pointer is not set to null. Causes the "wild pointer" to be produced.
After rule 1 has requested memory with malloc or new, you should immediately check that the pointer value is NULL. Prevents the use of memory with a pointer value of NULL.
Rule 2 Do not forget to assign an initial value to both arrays and dynamic memory. Prevents memory that is not initialized from being used as the right value.
"Rule 3" avoids array or pointer subscript out of bounds, especially beware of "more 1" or "less 1" operations.
"Rule 4" the request and release of dynamic memory must be paired to prevent a memory leak.
"Rule 5" after releasing memory with free or delete, immediately set the pointer to NULL to prevent the "wild pointer" from being produced.

Comparison of pointers to arrays:
In c++/c programs, pointers and arrays can be substituted for each other in many places, giving people an illusion that they are equivalent.
Arrays are either created in a static store (such as a global array) or created on a stack. The array name corresponds to (instead of pointing to) a piece of memory 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.

The following example compares the properties of pointers and arrays with strings.
1 Modifying content

In the following example, the capacity of the character array A is 6 characters, and the content is hello. The contents of a can be changed, such as a[0]= ' X '. The pointer p points to the constant string "world" (in the static store, the content is world), and the contents of the constant string cannot be modified. Syntactically, the compiler does not feel anything wrong with the statement p[0]= ' X ', but the statement attempts to modify the contents of the constant string to cause a run error.
#include <iostream.h>
void Main ()
{
Char a[] = "Hello";
A[0] = ' x ';
cout << a << Endl;
Char *p = "World"; Note P points to the constant string
P[0] = ' x '; The compiler cannot find the error
cout << p << Endl;
}

2 Content Replication and comparison

You cannot copy and compare directly to a group name. In the following example, if you want to copy the contents of array A to array B, you cannot use statement B = A, otherwise a compilation error will occur. The standard library function strcpy should be used for replication. Similarly, comparing the contents of B and A is the same, and cannot be judged by the IF (b==a), should be compared with the standard library function strcmp.
The statement p = A does not copy the contents of a pointer p, but assigns the address of A to P. To copy the contents of a, you can use the library function malloc for p to request a piece of memory with a capacity of strlen (a) + 1 characters, and then use strcpy for string copying. Similarly, the statement if (p==a) comparison is not the content but the address, should be compared with the library function strcmp.
Array...
Char a[] = "Hello";
Char b[10];
strcpy (b, a); Cannot use B = A;
if (strcmp (b, a) = = 0)//cannot be used if (b = = a)
...
Pointer...
int len = strlen (a);
Char *p = (char *) malloc (sizeof (char) * (len+1));
strcpy (P,a); Do not use P = A;
if (strcmp (p, a) = = 0)//Do not use if (p = = a)
...

3 Compute memory capacity
Use the operator sizeof to calculate the capacity (in bytes) of the array. In the following example (a), the value of sizeof (a) is 12 (be careful not to forget "). Pointer p points to a, but sizeof (p) has a value of 4. This is because sizeof (p) Gets the number of bytes of a pointer variable, which is equivalent to sizeof (char*), not the memory capacity referred to by P. The c++/c language has no way of knowing the memory capacity that the pointer refers to, unless you remember it when you request memory. 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. In the following example (b), sizeof (a) is always equal to sizeof (char *) regardless of the capacity of array A.
Example (a):
Char a[] = "Hello World";
char *p = A;
cout<< sizeof (a) << Endl; 12 bytes
cout<< sizeof (p) << Endl; 4 bytes

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

c++--Memory Usage

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.