初學者容易忘記申請內存的問題,在這裡記錄一下,以備自己粗心大意造成程序調試的麻煩。
/****************************有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申請內存的語句,當然不使用的時候也要釋放掉它,良好習慣嘛^_^。