C + + programming experience-returning a discussion of local variables

Source: Internet
Author: User

Return local Variables No problem if there is a problem with returning local variables, does the function have any meaning? Are global variables returned?
There is a problem returning a pointer to a local variable, and after the function is retired, the local variable disappears and the pointer points to an unknown area, so there is a problem. It is also absolutely not possible to return a reference to a local variable. The reference is just an alias of the variable, and the variable ontology does not exist, and the reference is of course meaningless.

Also, if it is a heap space, it can be returned, that is, the space that is requested in the function with new is returned.

But in general, the good style is:
Try to use new and delete in the same scope as possible, (that is, do not return the heap space), because if this is not the interface of your function is not flexible enough, imagine that each call your function of the person also need to remember to delete your function in the new heap space, otherwise it will cause a memory leak. What is returned is actually a value copy! Pointers are copies of pointer values and do not copy what is pointed to.

Never return the address of a local automatic variable from a function. If you really need to do this. You can pass in a pointer variable in the function's parameter table. The data that needs to be written is then written to the address that the pointer variable points to. Because the pointer points to a variable, the scope is outside the function body. Therefore, it will not be recycled at the end of the function.

Why is it impossible to return the address of a local variable within a function in the C language?
In a program, a variable that can be accessed only in a particular procedure or function is relative to a global variable.
A global variable, also known as an external variable, is defined outside the function and is scoped to the end of the program file, starting at the definition of the variable. The global variables are all stored in the static storage area, and when the program starts execution, the global variable is allocated the store, and the program line is released.
Local variables can have the same name as global variables, but local variables mask global variables. When a variable is referenced within a function, local variables of the same name are used instead of global variables.
A local variable is characterized by the creation of a destructor (destroy) at the end of a function when called with a function. Imagine that if a pointer to a local variable is returned, and the exact local variable is destroyed at the end of the function, but the pointer is not destroyed, it is returned, which means that the pointer is pointing to the object that was destroyed.
In general, a function can return a local variable. The scope of a local variable is only inside the function, and after the function returns, the local variable's memory is freed. Therefore, if the function returns the value of a local variable and no address is involved, the program does not make an error. However, if the address (pointer) of the local variable is returned, an error occurs after the program runs. Because the function just copies the pointer back, but the pointer to the content has been freed, so that the pointer to the content is unpredictable, the call will be an error. correctly, a function cannot return a pointer to the stack memory (note that this refers to the stack, which returns a pointer to the heap memory).

Here are some typical examples of how a function returns a local variable pointer:

1:

View Plaincopy to Clipboardprint?
  1. #include <stdio.h>
  2. Char *returnstr ()
  3. {
  4. Char *p="Hello world!";
  5. return p;
  6. }
  7. int Main ()
  8. {
  9. Char *str;
  10. Str=returnstr ();
  11. printf ("%s\n", str);
  12. return 0;
  13. }
This has no problem, because "Hello world!" is a string constant, stored in a read-only data segment, the first address of the read-only data segment that the string constant holds is assigned to the pointer, so when the RETURNSTR function exits, the memory of the string constant is not recycled, so the pointer can be accessed smoothly and without errors.

2:

View Plaincopy to Clipboardprint?
    1. #include   <stdio.h< span class= "tag" >>    
    2. char *returnstr ()     
    3. {&NBSP;&NBSP;&NBSP;
    4.     char p[]= "Hello  world! ";    
    5. &NBSP;&NBSP;&NBSP;&NBSP;RETURN&NBSP;P;&NBSP;&NBSP;&NBSP;
    6. }    
    7. int main ()    
    8. {   
    9. &NBSP;&NBSP;&NBSP;&NBSP;CHAR&NBSP;*STR;&NBSP;&NBSP;&NBSP;
    10.     str=returnstr ();    
    11.     printf ("%s\n",  str);    
    12.     return 0;   
    13. }&NBSP;&NBSP;&NBSP;
"Hello world!" Local variables are stored in the stack. When the RETURNSTR function exits, the stack is emptied, the memory of the local variable is emptied, so the function returns a memory address that has been freed, so it is possible to print out garbled characters.

3:

View Plaincopy to Clipboardprint?
    1. int func ()
    2. {
    3. int A;
    4. ....
    5. return A; Allow
    6. }
    7. int * FUNC ()
    8. {
    9. int A;
    10. ....
    11. Return &a; Meaningless and should not be done
    12. }

Local variables also branch automatic variables and local static variables, because a returns a value, so it is possible to return a local variable, whether automatic or static,

Because the value of this local variable is returned at this time, you should not return a pointer to a local auto variable, because the local automatic variable after the function call ends

Being discarded, this pointer points to an object that no longer exists and is meaningless. But you can return pointers to local static variables, because the existence of static variables

period from the definition to the end of the program.

4: If the return value of a function is not the address of a local variable, then the local variable must be declared as a static type. As follows: View Plaincopy to Clipboardprint?
  1. #include <stdio.h>
  2. Char *returnstr ()
  3. {
  4. static char p[]= "Hello world!";
  5. return p;
  6. }
  7. int main ()
  8. {
  9. Char *str;
  10. str=returnstr ();
  11. printf ("%s\n", str);
  12. return 0;
  13. }
5: An array cannot be the return value of a function because the compiler considers the array name to be the address of a local variable (array). Returning an array is usually replaced with a pointer to the array, and the pointer cannot point to an automatic array because the automatic array is discarded after the function ends, but a pointer to a static local array can be returned, since the static storage period is from the object definition to the end of the program. As follows:

View Plaincopy to Clipboardprint?
    1. int* func (void)
    2. {
    3. static int a[10];
    4. ........
    5. return A;
    6. }

6: It is possible to return pointers to heap memory

View Plaincopy to Clipboardprint?
  1. char *getmemory3 (int num)
  2. {
  3. char *p = (char *) malloc (sizeof (char) * num);
  4. return p;
  5. }
  6. void Test3 (void)
  7. {
  8. char *str = NULL;
  9. str = GetMemory3 (100);
  10. strcpy (str, "Hello");
  11. cout<< str << Endl;
  12. Free (str);
  13. }
The program uses malloc to request any amount of memory at run time, and the programmer is responsible for freeing up memory with free. The lifetime of dynamic memory is determined by the programmer himself and is very flexible to use.

C + + programming experience-returning a discussion of local variables (GO)

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.