What is a memory leak?

前端 未结 8 2158
无人共我
无人共我 2020-11-27 05:50

Obviously Wikipedia has a fair amount of information on the topic, but I wanted to make sure I understand. And from what I can tell it\'s important to understand the stack/h

8条回答
  •  长情又很酷
    2020-11-27 06:14

    A memory leak is simply dynamic memory that you allocate, but then never free. A consequence of this is that your program will slowly eat up memory over time, potentially causing a crash if you completely run out of physical memory and your swap gets completely eaten as well.

    So this is technically a memory leak:

    int main(void) {
        void *some_memory = malloc(400);
    
        // rest of program...
        // some_memory is never freed
    }
    

    But this is not:

    int main(void) {
        void *some_memory = malloc(400);
    
        // rest of program...
        free(some_memory);
    }
    

    Of course, this is a bit of a trivial example. More commonly, memory leaks occur in loops where several chunks of memory are allocated, but not all memory is freed. A common one is if you have a dynamically allocated struct containing a pointer to a dynamically allocated string - if you free the struct but forget to free the string, that is a memory leak. But note that your OS will clean up any allocated memory when your program terminates, so it won't permanently affect your memory.

    Dynamically allocating memory with functions such as malloc(), calloc(), and realloc(), but not using free(), will cause a memory leak. When you dynamically allocate memory, it is stored on the heap rather than the stack (the stack is used for static memory allocation such as local variables and the heap is used for dynamic memory allocation). When a function returns, values on the stack memory are reclaimed. However, the heap memory does not get reclaimed.

    Finally, leaked memory is memory that is no longer accessible and has not been freed / de-allocated.

提交回复
热议问题