top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the Best Pattern or Topology for avoid Memory Leaks in Projects?

+2 votes
633 views

What is the Best Pattern or Topology for avoid Memory Leaks in Projects

posted Oct 9, 2014 by Pushkar K Mishra

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+3 votes

There are two problems -
One is memory leak and another is memory corruption which are similar in the nature and we should always use the following topology -
1. Always nullify the pointer after free.
2. While free first check if it is null.
3. Use the smart pointer in C++ to avoid the dangling pointer (http://ootips.org/yonat/4dev/smart-pointers.html )
4. Always check the return of malloc to see if was succeeded
5. You can create a wrapper over malloc and free to to keep the track of count i.e. free count and allocated count on the following lines -

void *my_alloc (size_t size)
{
    void *p;

    p = malloc(size);
    if (p)
    {
        my_count_alloc++;
    }
    else
        return null;

    return (p);
}

void my_free (void *p)
{
    if (p)
    {
        free(p);
        my_count_free++;
    }
}

and at the end u can match the free count to the allocated count.

answer Oct 9, 2014 by Salil Agrawal
+2 votes

there are three parts -
1. why/when/where you are allocating,
2. what is the lifetime of object
3. and last why/when/where you want to free it.

Before allocating you should be very clear about these three parts.
To work in multi-threaded application, there is reference counting, weak pointers etc
(http://www.codingwisdom.com/codingwisdom/2012/09/reference-counted-smart-pointers-are-for-retards.html).
(do read the discussions also)

answer Oct 9, 2014 by Sumit Jindal
Similar Questions
+1 vote

I'm beginner to LTE and I wanted to know basics of it. Please suggest me the links so that I can analyze some basics.

+1 vote
1
4     1
27    8     1
256   81    16   1
3125  1024  143  32   1
+4 votes

How do you avoid memory leaks in an android application?

0 votes

I have a requirement in my project which requires a very high throughput. I need to choose a programming language for this project. Want to know the opinion if the people which language to select keeping the fact that development should be fast and throughput is not compromised.

...