C Language Learning 017: malloc and free, 017 malloc
Both malloc and free are included in the <stdlib. h> header file.
Because local variables are stored in the stack, once the function is left, the variables will be released. When we need to persistently use the data, we need to save the data to the heap, the malloc method is required to apply for memory space in the heap. the malloc method creates a memory space in the heap and returns a pointer, which is of the void * type, saves the actual address of the memory.
Folder * f = malloc (sizeof (folder); // the sizeof informs the System of the space occupied by the folder data type in the system.
Free is used in combination with malloc. Once the space created by malloc is unnecessary, it needs to be released through free. Otherwise, it will easily cause memory leakage. Just pass the pointer to the free function.
Free (f );
1 # include <stdio. h> 2 # include <stdlib. h> 3 4 typedef struct folder {5 int level; 6 char * filename; 7 struct folder * child; 8} folder; 9 10 int main () {11 folder * f = malloc (sizeof (folder); // the sizeof informs the System of the space occupied by the folder data type in the system 12 f-> level = 1; 13 f-> filename = "first"; 14 f-> child = NULL; 15 printf ("% s level is % I", f-> filename, f-> level); 16 free (f); 17 return 0; 18}