Re: cString operator= with same buffer

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Holger Brunn wrote:
> Jon Burgess on Sunday 20 November 2005 18:17:
> 
>>Doesn't this cause a memory leak? It'll strdup() the old string and then
>>lose the old pointer to it. 
> 
> 
> Hello,
> as far as I can see, there wouldn't be a mem leak - as both cStrings point to 
> the same buffer, you only loose one of them. The one that was assigned from 
> still has a pointer to the original buffer (and its destructor will free it).

In the normal case you'd be correct, the destructor would be called 
twice and free up both, but in the case that the cStrings are equal the 
destructor will only be called once on the new cString. There is nothing 
which will destruct the old cString. I wrote the quick test app as 
attached and valgrind seems to agree with me.

[jburgess@shark cstring]$ g++ -g -O2 -Wall -o main main.c
[jburgess@shark cstring]$ ./main
operator= called
Hello World
[jburgess@shark cstring]$ valgrind --tool=memcheck ./main
==18765== Memcheck, a memory error detector.
==18765== Copyright (C) 2002-2005, and GNU GPL'd, by Julian Seward et al.
==18765== Using LibVEX rev 1367, a library for dynamic binary translation.
==18765== Copyright (C) 2004-2005, and GNU GPL'd, by OpenWorks LLP.
==18765== Using valgrind-3.0.1, a dynamic binary instrumentation framework.
==18765== Copyright (C) 2000-2005, and GNU GPL'd, by Julian Seward et al.
==18765== For more details, rerun with: -v
==18765==
operator= called
Hello World
==18765==
==18765== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 9 from 4)
==18765== malloc/free: in use at exit: 12 bytes in 1 blocks.
==18765== malloc/free: 2 allocs, 1 frees, 24 bytes allocated.
==18765== For counts of detected errors, rerun with: -v
==18765== searching for pointers to 1 not-freed blocks.
==18765== checked 196608 bytes.
==18765==
==18765== LEAK SUMMARY:
==18765==    definitely lost: 12 bytes in 1 blocks.
==18765==      possibly lost: 0 bytes in 0 blocks.
==18765==    still reachable: 0 bytes in 0 blocks.
==18765==         suppressed: 0 bytes in 0 blocks.
==18765== Use --leak-check=full to see details of leaked memory.

	Jon

-------------- next part --------------
A non-text attachment was scrubbed...
Name: main.c
Type: text/x-csrc
Size: 1169 bytes
Desc: not available
Url : http://www.linuxtv.org/pipermail/vdr/attachments/20051120/96eb5671/main.c

[Index of Archives]     [Linux Media]     [Asterisk]     [DCCP]     [Netdev]     [Xorg]     [Util Linux NG]     [Xfree86]     [Big List of Linux Books]     [Fedora Users]     [Fedora Women]     [ALSA Devel]     [Linux USB]

  Powered by Linux