It is easy for beginners to forget the issue of applying for memory. Here we will record it for your carelessness to cause trouble in program debugging.
/**************************** Programs with bugs ******* *********************/
#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;}
A netizen sent the simple code above to the QQ group and said, what is wrong? Why is it not like a wrong program? However, the result of a single operation is the result of a response. This is the reason why the memory has not been successfully applied. The operating system does not allow you to execute the application, because it may have accessed the address that should not be accessed. Pointer, sometimes brutal, need to be used with caution.
/**************************** Bug-free programs ******* *********************/
#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;}
The modified program is the above statement that adds malloc to apply for memory. Of course, it should be released when it is not used. It is a good habit to use it ^_^.