C Language Learning 017: malloc and free, 017 malloc

Source: Internet
Author: User

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}

Related Article

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.