POV-Ray : Newsgroups : povray.off-topic : Smart little programming tricks, where to find ? : Re: Smart little programming tricks, where to find ? Server Time
11 Oct 2024 01:22:03 EDT (-0400)
  Re: Smart little programming tricks, where to find ?  
From: Nicolas Alvarez
Date: 19 Mar 2008 13:01:41
Message: <47e15505$1@news.povray.org>
Warp escribió:
> stbenge <stb### [at] hotmailcom> wrote:
>> I don't find it too difficult to delete every "new".
> 
>   You would be surprised.
> 
>   There's a potential memory leak here:
> 
> void foo()
> {
>     char* s = new char[100];
>     bar();
>     delete[] s;
> }

If bar throws an exception, s won't be deleted. It can be avoided by 
using a smart pointer.

>   There's a potential memory leak here:
> 
> class A
> {
>     char* s;
> 
>  public:
>     A(): s(new char[100]) {}
>     ~A() { delete[] s; }
> };

Erm... No idea :) I know it could cause a double-free if you copy the 
object, since it doesn't have an explicit copy constructor and the 
default one doesn't do what we want in this case; but I don't know what 
could cause a leak.

>   Naturally both of these leaks can be fixed by using cleaner code:
> 
> void foo()
> {
>     std::string s(100, ' ');
>     bar();
> }
> 
> class A
> {
>     std::string s;
> 
>  public:
>     A(): s(100, ' ') {}
> };

Of course a string is better for this particular case :) Also avoids 
many possible buffer overflows (thought not all; operator[] is unchecked).


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.