function returns local variable

Source: Internet
Author: User

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:

#include <stdio.h> char *returnstr () {     char *p= "Hello world!";     return p; } int main () {     char *str;     Str=returnstr ();     printf ("%s\n", str);     return 0; }
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:

#include <stdio.h> char *returnstr () {     char p[]= "Hello world!";     return p; } int main () {     char *str;     Str=returnstr ();     printf ("%s\n", str);     
"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:
int func () {      int A;      ....      return A;    Allow}                   int * func () {      int A;      ....      Return &a;    

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:
 #include <stdio.h> char *returnstr () {static char p[]= "Hello world!"; return p;      } int main () {char *str;     Str=returnstr ();     printf ("%s\n", str); return 0; } 
5: An array is not a return value for a function because The compiler takes the array name as 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.
int* func (void) {    static int a[10];    ........    

6: It is possible to return pointers to heap memory

char *getmemory3 (int num) {char *p = (char *) malloc (sizeof (char) * num); return p;} void Test3 (void) {char *str = NULL;STR = GetMemory3 (+); strcpy (str, "hello");cout<< str << endl;free (str);}
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.

function returns local variable

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.