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