function pointer passing

Source: Internet
Author: User

voidGetMemory (Char*p,intnum) {P= (Char*)malloc(sizeof(Char)*num); inti =0;}intMainintargcChar**argv) {/*char buf1[] = "123";    AA (BUF1); */    Char*str =NULL; GetMemory (str, -); return 0;}

Looking at this example, the function GetMemory obviously cannot allocate memory to STR, and it can also cause a memory leak.

Analyze the process:

1. Declare and define the STR,STR address as 0x00000000;

2. Enter the function. Copy str to P, that is, p is just a copy of STR, with the address value of str: 0x00000000;

3.malloc began to allocate memory, after the allocation succeeds, P's address is certainly not the original 0x00000000, what is not important, anyway definitely not the address of Str.

4. function is finished, return. Memory must be allocated successfully, the original p is pointing to the memory pointer, but does not assign to str this operation, so STR is still the original 0x00000000.

Char *getmemory (int  num) {    char *p = (char *)malloc(  sizeof(char) * num);     return p;}

Look at this function, in main, fill in a sentence, Char *str=getmemory (100);

1.P is defined, a memory is allocated, and P points to that memory. P this pointer is on the stack, and there is a heap in that paragraph;

2. The function returns p, at which point copies the p, that is, the function produces a copy of P, and the address of P is returned to Str.

3. Congratulations STR successfully led the memory!

You can give Str a clap!

function pointer passing

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.