Memory Application Problems

Source: Internet
Author: User

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 ^_^.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.