zoukankan      html  css  js  c++  java
  • 申请内存的问题

       初学者容易忘记申请内存的问题,在这里记录一下,以备自己粗心大意造成程序调试的麻烦。

    /****************************有bug的程序****************************/

    #include <stdio.h>
    #include <stdlib.h>
    #include <fcntl.h>

    struct person {
        int age ;
        char name;
    };

    struct student {
        struct person abc;
        int id;
    };

    struct student *f1;

    int main(void)
    {
        f1->id = 20;
        printf("%d ", f1->id);

        f1->abc.age = 20;
        printf("%d ", f1->abc.age);

        return 0;
    }

        有个网友将上面这段简单的代码发到QQ群上说,到底哪里有错?怎么看都不像有错的程序呀?但是一运行就是出不来结果。这正是内存没有申请成功的原因,操作系统不让你执行,因为可能访问到了不该访问的地址。指针嘛,有时候挺野蛮的,需要慎重使用。

    /****************************无bug的程序****************************/

    #include <stdio.h>
    #include <stdlib.h>
    #include <fcntl.h>

    struct person {
        int age ;
        char name;
    };

    struct student {
        struct person abc;
        int id;
    };


    int main(void)
    {
        struct student *f1 = (struct student *)malloc(sizeof(struct student));
        f1->id = 20;
        printf("%d ", f1->id);
     
        f1->abc.age = 20; 
        printf("%d ", f1->abc.age); 

        free(f1);
        return 0;
    }

        修改后的程序如上,就是加多了malloc申请内存的语句,当然不使用的时候也要释放掉它,良好习惯嘛^_^。

  • 相关阅读:
    MySQL执行计划解读(转载)
    排序算法
    Linux下在防火墙中开启80端口、3306端口
    Android APN
    PB之——DropDownListBox 与 DropDownPictureListBox
    CSS总则。
    WIN7系统中设置默认登录用户
    Javascript日期比较
    myeclipse中UTF-8设置
    webview loadUrl() 弹出系统浏览器解决办法
  • 原文地址:https://www.cnblogs.com/snake-hand/p/3162835.html
Copyright © 2011-2022 走看看