What is a memory leak? (What is a memory leak?)

Source: Internet
Author: User

What is the memory leak in the program?

We have written many programs with the keyword Free (). For example, I am in this post about some of the important operations of the list (Important operations on a Linked list) to delete the entire list of this function, the code snippet is as follows:

struct node * deletelist (struct node * head) {    struct node * temp;      while (Head! = NULL)    {        = head;         = Head , next;          Free (temp);    }     return NULL;}

When we allocate memory in the program, we do not automatically release the manually allocated memory after the program finishes, so we also have to manually release our allocated memory. In some cases, a memory leak occurs when the program continues to run. A memory leak occurs when the programmer allocates memory in the heap and forgets to release it. A long-running program memory leak is a serious problem for programs such as Daemons and servers.

The following is an example of a memory leak code:

voidfunc () {//In the below line we allocate memory    int*ptr = (int*)malloc(sizeof(int)); /*Do some*/     return;//Return without freeing ptr}//We returned from the function but the memory remained allocated.//This wastes memory space.

Avoid the correct code for memory leaks:

void func () {    ///  We Allocate memoryin the next line    int *ptr = (intm Alloc(sizeof(int));      /*  *     / // We unallocate memoryin the next line free     (PTR);      return ;}
Releasing your own allocated memory is a good habit in C language.

What is a memory leak? (What is a memory leak?)

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.