Malloc:
1. malloc allocates new memory and uses parameters to bring back the applied memory pointer (the second-level pointer is required or the returned memory pointer is used)
Error program: # include <stdio. h> # include <stdlib. h> void getmemory (char * P) {P = (char *) malloc (100); strcpy (P, "Hello World");} int main () {char * STR = NULL; getmemory (STR); printf ("% s/n", STR); free (STR); Return 0 ;}
Running result: the program crashes. the malloc in getmemory cannot return dynamic memory. Free () is dangerous for STR operations.
Cause Analysis: // malloc (STR) is a value transfer operation for the pointer Str. STR is copied in getmemory and cannot return the requested memory address through the parameter, STR is still null. The free (null) operation is dangerous. // Malloc () in the getmemory function allocates a new memory to P. After the function is executed, P cannot be found because STR does not get the P value, as a result, the newly allocated memory pointed to by P is not free and the memory leaks.
Correct Solution: # include <stdio. h> # include <string. h> # include <stdlib. h> void getmemory (char ** p) {* P = (char *) malloc (100); strcpy (* P, "Hello World");} int main () {char * STR = NULL; getmemory (& Str); printf ("% s \ n", STR); free (STR); Return 0 ;}or:
#include <stdio.h>#include <string.h>#include <stdlib.h>char* getmemory(char *p){ p=(char *) malloc(100); strcpy(p,"hello world"); return p;}int main( ){ char *str=NULL; str=getmemory(str); printf("%s\n",str); free(str); return 0;}