Hi, all
Like i asked before, This thread is about Memory Leak.
I am a beginner in c++ and want to become a senior programmer. When i was coding, i found the memory leak is happening everywhere and maybe some senior programmer also have this problem.
So i want to start a thread, let's talk about the memory leak. And throw some examples if you want.
Let me begin first:
Pointer assignment memory leak:

char *a= new char[10];
char *b=new char[10];
b=a;
delete[]b;

In fact, this pointer assignment free the dynamic variable associated with pointer a. It will never free b.

So this is my example. You guys could give your example.
I know there have a bunch of articles about this topic. But since there have a lot of expert here, so i was thinking maybe we could learn more from here.
Thanks.

Recommended Answers

All 2 Replies

It's a bit difficult to give an example of memory leak, because it almost always happens accidently without the developer even knowing it. Memory leaks bugs almost always plant themselves so subtly that they are often too difficult to trace even for an experienced programmer and the only way he comes to know about them is through the (in)famous "segmentation fault" which is when the system runs out of available memory.

@shasha82110: You can mark the other thread as solved so people know where to post.

Hmm, an example of a memory leak.

int main() {
  int **a = new int*[10];

  for (int i = 0; i < 10; ++i)
    a[i] = new int[5];

  /* Do stuff with a */

  for (int i = 0; i < 10; ++i)
    delete[] a[i];
}

In this example, you freed the data each pointer was pointing at, but you fergot to free the space which was allocated for the pointers themselves. To fix this leak, you need to remember to free a.

delete[] a;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.