Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do ensure that while writing C++ code itself it will not cause any memory leaks?

Running valgrind or purify would be the next steps But while while writing the code itself how do you ensure that it will not cause any memory leaks? You can ensure following things:- 1: Number of new equal to delete 2: Opened File descriptor is closed or not

Is there any thing else?

like image 735
anish Avatar asked Aug 20 '09 12:08

anish


People also ask

What causes a memory leak in C?

In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in such a way that memory which is no longer needed is not released. A memory leak may also happen when an object is stored in memory but cannot be accessed by the running code.

How can you prevent memory leak in C which you would have allocated using dynamic?

The only way to avoid memory leak is to manually free() all the memory allocated by you in the during the lifetime of your code. You can use tools such as valgrind to check for memory leaks. It will show all the memory that are not freed on termination of the program.

Which tool gives the information about memory leaks in C programs?

Valgrind is a multipurpose code profiling and memory debugging tool for Linux when on the x86 and, as of version 3, AMD64, architectures. It allows you to run your program in Valgrind's own environment that monitors memory usage such as calls to malloc and free (or new and delete in C++).


1 Answers

Use the RAII idiom everywhere you can

Use smart pointers, e.g. std::auto_ptr where appropriate. (don't use auto_prt in any of the standard collections as it won't work as you think it will)

like image 98
Glen Avatar answered Oct 21 '22 04:10

Glen