Step into the minefield of C ++-C ++ memory management (II)

Source: Internet
Author: User
4. How does the pointer Parameter Pass the memory?

If the function parameter is a pointer, do not expect this pointer to apply for dynamic memory. In Example 7-4-1, the getmemory (STR, 200) Statement of the test function does not enable STR to obtain the expected memory. STR is still null. Why?

Void getmemory (char * P, int num)
{
P = (char *) malloc (sizeof (char) * num );
}
Void test (void)
{
Char * STR = NULL;
Getmemory (STR, 100); // STR is still null
Strcpy (STR, "hello"); // running error
}

Example 4.1 try to apply for dynamic memory with pointer Parameters

The fault lies in the getmemory function. The compiler always needs to make a temporary copy for each parameter of the function. The copy of the pointer parameter P is _ p, and the compiler makes _ p = P. If the program in the function body modifies the content of _ p, the content of parameter P is modified accordingly. This is why pointers can be used as output parameters. In this example, _ P applied for a new memory, but changed the memory address indicated by _ p, but P was not changed at all. Therefore, the getmemory function cannot output anything. In fact, each execution of getmemory will leak a piece of memory, because the memory is not released with free.

If you have to use the pointer parameter to request memory, you should use "pointer to Pointer" instead. See example 4.2.

Void getmemory2 (char ** P, int num)
{
* P = (char *) malloc (sizeof (char) * num );
}
Void Test2 (void)
{
Char * STR = NULL;
Getmemory2 (& STR, 100); // note that the parameter is & STR, not Str
Strcpy (STR, "hello ");
Cout <STR <Endl;
Free (STR );
}

Example 4.2 apply for dynamic memory with a pointer pointing to the pointer

Because the concept of "pointer to Pointer" is not easy to understand, we can use function return values to transmit dynamic memory. This method is simpler. See example 4.3.

Char * getmemory3 (INT num)
{
Char * P = (char *) malloc (sizeof (char) * num );
Return P;
}
Void test3 (void)
{
Char * STR = NULL;
STR = getmemory3 (100 );
Strcpy (STR, "hello ");
Cout <STR <Endl;
Free (STR );
}

Example 4.3 use function return values to transmit dynamic memory

Although it is easy to use the function return value to pass dynamic memory, some people often use the return statement wrong. It is emphasized that the return statement should not be used to return the pointer pointing to the "stack memory" because the function exists in it automatically disappears at the end, as shown in example 4.4.

Char * getstring (void)
{
Char P [] = "Hello World ";
Return P; // the compiler will give a warning
}
Void test4 (void)
{
Char * STR = NULL;
STR = getstring (); // STR content is junk
Cout <STR <Endl;
}

Example 4.4 Return Statement returns a pointer to "stack memory"

Use the debugger to track test4 step by step. After executing the STR = getstring statement, STR is no longer a null pointer, but the STR content is not "Hello World" but garbage.
What if I rewrite example 4.4 to example 4.5?

Char * getstring2 (void)
{
Char * P = "Hello World ";
Return P;
}
Void test5 (void)
{
Char * STR = NULL;
STR = getstring2 ();
Cout <STR <Endl;
}

Example 4.5 Return Statement returns a constant string

Although the function test5 runs without errors, the design concept of the function getstring2 is incorrect. Because "Hello World" in getstring2 is a constant string located in the static storage zone, it remains unchanged during the lifetime of the program. No matter when getstring2 is called, it returns the same read-only memory block.

  5. Eliminate "wild pointer"

The "wild pointer" is not a null pointer, but a pointer to the "junk" memory. Generally, null pointers are not incorrectly used, because if statements are easy to judge. However, the "wild Pointer" is very dangerous, and the IF statement does not work for it. There are two main causes of "wild pointer:

(1) pointer variables are not initialized. When a pointer variable is created, it does not automatically become a null pointer. Its default value is random, which means it is random. Therefore, the pointer variable should be initialized at the same time when it is created, either set the pointer to null or set it to direct to the legal memory. For example

Char * P = NULL;
Char * STR = (char *) malloc (100 );

(2) After the pointer P is free or deleted, It is not set to null, which makes people mistakenly think P is a valid pointer.

(3) pointer operations go beyond the scope of variables. This situation is hard to prevent. The example program is as follows:

Class
{
Public:
Void func (void) {cout <"func of Class A" <Endl ;}
};
Void test (void)
{
A * P;
{
A;
P = & A; // note the life cycle of
}
P-> func (); // P is a "wild pointer"
}

When the function test executes the statement p-> func (), object A has disappeared, and P points to a, so P becomes a "wild pointer ". But the strange thing is that I did not encounter any errors when running this program, which may be related to the compiler.

 

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.