Standard library functions Malloc/calloc/realloc and free heap memory allocation and recycling
1 /*2 * malloc Practice3 *4 * */5 6#include <stdlib.h>7#include <stdio.h>8 9 intMain ()Ten { One int*p_value =NULL; A -P_value = (int*)malloc(1*sizeof(int)); - if(p_value) { theprintf"P_value is 0x%p\n .", p_value); -printf"*p_value is%d\n .", *p_value); - Free(p_value); -P_value =NULL; + } - } + A return 0; at}
1 /*2 * CALLOC (), realloc () practice3 *4 * Different from Malloc,calloc will initialize the open storage space to 05 *6 * */7 8#include <stdlib.h>9#include <stdio.h>Ten One intMain () A { - int*p_value = (int* )calloc(4,sizeof(int)); - //(int *) malloc (4 * sizeof (int)); the if(p_value) { -printf"P_value is 0x%p\n .", p_value); -printf"*p_value is%d\n .", *p_value); - void*pointer =NULL; +pointer =realloc(P_value,6*sizeof(int)); - //realloc (p_value, 0); the actual effect is equal to the statement free (p_value); + //P_value = NULL, ReAlloc (P_value, 4*sizeof (int)), and the actual effect is A //equals Statement p_value = NULL, p_value = (int *) malloc (4*sizeof (int)); at if(pointer) { -P_value = (int*) pointer; - } -printf"P_value is 0x%p\n .", p_value); -printf"*p_value is%d\n .", *p_value); - Free(p_value); inP_value =NULL; - } to}
1 /*2 * input:12343 * output:43214 * */5 6#include <stdio.h>7#include <stdlib.h>8 9 intMain ()Ten { Onetypedefenum{N, Y} en_retry; A -En_retry over =N; - int*p_integer =NULL; the int*p_integers[ -] ={NULL}; - - intCounter =0; - Do { +P_integer = (int*)malloc(sizeof(int) *1); - if(P_integer) { +printf"Input an Integer"); Ascanf"%d", P_integer); atp_integers[counter++] =P_integer; - } -printf"another? [y/n]"); -printf"%d\n", over); -scanf"%d", &Over ); -printf"%d\n", over); in} while(over); - to for(--counter; Counter >=0; counter--) { +printf"%d\t", *P_integers[counter]); - Free(P_integers[counter]); the } *printf"\ n"); $ Panax Notoginseng return 0; -}
Standard C Episode 10