zoukankan      html  css  js  c++  java
  • C语言学习017:malloc和free

      malloc和free都包含在<stdlib.h>头文件中

      局部变量由于存储在栈中,一旦离开函数,变量就会被释放,当我们需要将数据持久使用,就需要将数据保存到堆中,而在堆中申请内存空间就需要malloc方法;malloc方法在堆中建立一片内存空间,然后返回一个指针,这个指针是void*类型,保存了这片内存的其实地址

        folder* f=malloc(sizeof(folder));//通过sizeof告诉系统folder数据类型在系统中占用的空间大小

      free是和malloc配对使用的,一旦malloc创建的空间不需要了就需通过free释放,如果不这样做很容易造成内存泄漏;将指针传递给free函数就行

        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));//通过sizeof告诉系统folder数据类型在系统中占用的空间大小
    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 }
  • 相关阅读:
    SPOJ 8093 JZPGYZ
    UVA1030 Image Is Everything
    UVA11996 Jewel Magic
    UVA11922 Permutation Transformer
    UVA1479 Graph and Queries
    P3224 [HNOI2012]永无乡
    UVA11020 Efficient Solutions
    UVA12206 Stammering Aliens
    UVA11107 Life Forms
    UVA11019 Matrix Matcher
  • 原文地址:https://www.cnblogs.com/liunlls/p/C_malloc_free.html
Copyright © 2011-2022 走看看