top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is memory leak and how it should be avoided using c?

0 votes
676 views
What is memory leak and how it should be avoided using c?
posted May 1, 2017 by Neeraj Kumar

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

2 Answers

+1 vote

Memory leak is the situation when a process allocates memory from the heap during the run time and forgot to release this allocated memory block back to heap. This may result crunch of memory or unavailability of memory for a process.
void * malloc(#of bytes);
free(pointer to block memory);

answer May 1, 2017 by Vikram Singh
0 votes

Adding on top of what Vikram has said, to avoid the memory leak

Rule 1: Always write “free” just after “malloc”

int *p = (int*) malloc ( sizeof(int) * n );
....
....
free (p);

Now go in between and write your code:

Rule 2: Never, ever, work with the allocated pointer. Use a copy!

int *p_allocated = (int*) malloc ( sizeof(int) * n );
int *p_copy = p_allocated;
// do your stuff with p_copy, not with p_allocated!
// e.g.:
while (n--) { *p_copy++ = n; }
...
free (p_allocated);

Rule 3: Use valgrind or purify to find the leak.

answer May 1, 2017 by Salil Agrawal
...