Hi, all
i am reading some memory leaking problem articles now.
Here is one question i can't understand:

char *a= new char[10];
char *b= new char[10];
b=a;//pointer assignment
delete []b;

In this article, it mentioned that the pointer assignment have side-effect and we couldn't delete pointer b from heap anymore.
its better use strcpy(b,a) function.

My question is:
is that correct??
if we couldn't delete b from heap what's the

delete []b;

used for??
And why the last line of the code free the dynamic variable associated with pointer a??

Thanks.

It's saying that you can't delete the original "b" anymore because you've lost it's address by assigning a to b, which overwrites the previous address that b was holding. So the last line frees the original a, since b now points to a.

Since you assign the value in "a" to "b" you effectively lose the address of the char [] pointed to by "b." You can delete the value pointed to by "b," which will be the same char [] pointed to by "a," but you cannot access the other char [] since you have no pointer to it.

The above two posts have already informed you about the "side-effect" of the pointer assignment. I just want to add to it that would throw some light on the memory leak part.
When you permanently loose the base address of the memory chunk pointed to by b, you also loose your chance to free that memory, since to free any memory in langauges such as C/C++ you would absolutely need the pointer to it. Now, since you cannot free this memory and since it cannot be reclaimed by the language on it's own (like langauges that do offer such mechanism - Java) this chunk of memory is permamnently lost from the available pool of memory for your program. This memory has "leaked/drained" from the memory pool, and hence this is called memory leak. Too many such "leaks" would ultimately cause the pool to get exhausted and what you would get is an introduction to the famous "segmentation fault".

I was thinking maybe we should throw one thread about memory leak on the DANIWEB.
Its really important for beginners.

Why not you can go ahead and start one. I am sure there are enough C/C++ "gurus" who might be able to throw much more light on that subject and also bring out a few things that many of us still don't know.

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.