Use pointers to do function return value __ function

Source: Internet
Author: User

use a pointer to do a function return value

1. When using the pointer as the return value of the function, the char *p at the main function will get the value of the calling function char *pf, that is, an address value, such as oxAE72. At this point we need to note whether the address value points to the existence of the space (that is, the operating system declaration has been registered, will not be released, that may be modified by other operations);
2, the use of stack memory return pointer is obviously wrong, because stack memory will be automatically released after the call, so that the main function to use the address space will be very dangerous.
3. It is correct to use the heap memory return pointer, but note that a memory leak problem may occur and release the memory in the main function after use.

The address that the P pointer refers to is not in the stack area (memory in the stack area is automatically released by the compiler, and the heap area is released by the system when the programmer or program ends)

Note: You cannot use free if you are not using malloc.

#include <stdio.h>
#include <stdlib.h>
char* getmemory () 
{ 
	//char p[] = "HI"; 
	Char *p= (char *) malloc (sizeof (char));//"Hello World"; 
	return p; 
}           
int main () 
{ 
	char *str = getmemory ()//Error! Get a piece of freed memory 
	printf ("\naddress of function display is%u", str); 
 free (str);
	Str=null;
	return 0;
}


After free you need null, just a habit, as long as you can guarantee that free will not continue to use after the line.
Set to null immediately after free, if the program is accidentally used, it will be killed immediately. However, if you do not set NULL, you may have a variety of strange problems if you use it accidentally.
Free is null, just a habit.

Free (p) post-pointer problem

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.