On the transmission of dynamic memory between C/C ++ Functions

Source: Internet
Author: User

When you are involved in C/C ++ core programming, you will have no end to dealing with memory management. These will often make people suffer. So if you want to go deep into C/C ++ programming, you must calm down and have a hard time.
Now we will discuss which book in C/C ++ I think is not completely clear, and it is also the transfer of dynamic memory that involves the most conceptual details and one of the most difficult technologies in the language. In addition, many professionals in software development cannot write relevant qualified code.

I. Introduction

Let's take a look at the example below. This is what we often expect when writing library functions or common functions in projects.

Void MyFunc (char * pReturn, size_t size)

{.........

PReturn = (char *) malloc (sizeof (char) * num );.........

} We can clearly see the intent of the Code author. He wants to declare a pointer char * pMyReturn = NULL in the function call; call MyFunc and return a dynamic memory with a length of size.

So can the author achieve the expected results?

So I can tell the author that his program was lucky to pass during the compilation period, but his program crashed and ended at runtime. The reason is that he has violated the irrevocable terms of the system: incorrectly operating the memory.

Ii. Knowledge about memory operations and Problems

To completely solve the problem of dynamic memory transfer, let's first review the knowledge points of memory management.

(1) There are three memory allocation methods:

Allocated from the static storage area. The program has been allocated when it is compiled, and the program exists throughout the entire runtime. For example, global variables and static variables.

Create on stack. When a function is executed, the storage units of local variables in the function can be created on the stack. When the function is executed, these storage units are automatically released. Stack memory allocation computation is built into the processor's instruction set, which is highly efficient, but the memory capacity allocated is limited.

Allocated from the stack, also known as dynamic memory allocation. When the program runs, it uses malloc or new to apply for any amount of memory. The programmer is responsible for releasing the memory with free or delete. The lifetime of the dynamic memory is determined by us and the usage is flexible.

(2) pointer operation process

Apply for and initialize or set to NULL:

Int * pInt = NULL; open up space or point it to an object:

PInt = new Int (3); or int I = 3; pint = & I; use a pointer (more specifically, to operate the memory, add if (pint! = NULL) or assert (pInt! = NULL) before use, in case the memory application fails to use the pointer ):

If (p! = NULL) {use pint}; release the used memory

Free (pInt); NULL for pointer

PInt = NULL; (avoid the emergence of wild pointers)

(3) In parameter passing of a function, the compiler always creates a temporary copy for each parameter of the function. If the parameter is p, the compiler will generate a copy of p _ p, make _ p = p; if the program in the function body modifies the content of _ p, the content of parameter p will be modified accordingly. This is why pointers can be used as output parameters.

Iii. Problem Analysis

Based on the above rules, we can easily analyze the cause of failure in the example.

Void MyFunc (char * pReturn, size_t size)

{.........

PReturn = (char *) malloc (sizeof (char) * num );.........

} Void main (void) {char * pMyReturn = NULL; MyFunc (pMyReturn, 10);} In MyFunc (char * pReturn, size_t size) _ pMyReturn actually applied to the memory, pMyReturn applied for a new memory, but changed the memory address indicated by _ pMyReturn, but pMyReturn was not changed at all. Therefore, the function MyFunc cannot output anything. In fact, each execution of MyFunc exposes a piece of memory, because the memory is not released with free.

Iv. Problem Solutions

There are three solutions for transferring dynamic data between functions.

Method 1: If we use C ++ for programming, we can easily use the reference technology. I also strongly recommend that you use references because they will make you fewer mistakes. The following is an example.

Void MyFunc (char * & pReturn, size_t size) {pReturn = (char *) malloc (size); memset (pReturn, 0x00, size ); if (size> = 13)

Strcpy (pReturn, "Hello World! ");}

Void main () {char * pMyReturn = NULL; MyFunc (pMyReturn, 15); if (pMyReturn! = NULL)

{Char * pTemp = pMyReturn; while (* pTemp! = ''\ 0 '')

Cout <* pTemp ++; pTemp = NULL; strcpy (pMyReturn, "AAAAAAAA"); free (pMyReturn); pMyReturn = NULL;} Method 2: using a second-level pointer

Void MyFunc (char ** pReturn, size_t size)

{* PReturn = (char *) malloc (size);} void main (void)

{Char * pMyReturn = NULL; MyFunc (& pMyReturn, 100); // note that the parameter is & pMyReturn if (pMyReturn! = NULL) {strcpy (pMyReturn, "hello"); cout <pMyReturn <endl; free (pMyReturn); pMyReturn = NULL;} Why is the second-level pointer ready. The cause can be easily analyzed by using function transfer rules. We passed & pMyReturn, that is, the content of the double pointer is passed to the function. The function process changes the pointer content so that pMyReturn clearly points to the opened memory.

Method 3: Use function return values to transmit dynamic memory

Char * MyFunc (void)

{Char * p = new char [20]; memset (p, 0x00, sizeof (p); return p;} void main (void)

{Char * str = NULL; str = MyFunc (); if (str! = NULL)

{Strcpy (str, "Hello, baby"); cout <str <endl; free (str); str = NULL;} note that the function is written in this way, you cannot return any dynamic memory because p points to a String constant. The content is allocated in the static storage area and cannot be changed. (If you want to get dynamic memory, we must see malloc or new ).

Char * MyFunc (void)

{Char * p = "Hello World"

Return p;} conclusion

Operating memory is a challenge for C/C ++. We are a professional software developer. You should have an in-depth understanding of and be able to flexibly master pointer and memory operations.

 

From bored blogs

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.