当前位置:编程学习 > C/C++ >>

申请内存的问题

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

/****************************有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 \n", f1->id);

    f1->abc.age = 20; 
    printf("%d \n", 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 \n", f1->id);
 
    f1->abc.age = 20; 
    printf("%d \n", f1->abc.age); 

    free(f1);
    return 0;
}


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

 

补充:软件开发 , C语言 ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,