delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/07/09/16:13:38

Date: Thu, 9 Jul 1998 16:12:12 -0400 (EDT)
Message-Id: <199807092012.QAA25515@delorie.com>
From: DJ Delorie <dj AT delorie DOT com>
To: lwithers AT lwithers DOT demon DOT co DOT uk
CC: djgpp AT delorie DOT com
In-reply-to: <ivglrCA7V$o1Ew74@lwithers.demon.co.uk> (message from Laurence
Withers on Wed, 8 Jul 1998 23:40:59 +0100)
Subject: Re: "delete" and "delete []" operators

>   x = new char[15];
> 
> Should I then, when I come to free the memory, use:
> 
>   delete x;
> or
>   delete [] x;

You should use delete [] x, but for obscure reasons.  Here's some
background.

The difference between delete and delete [] can be best described by
this example:

	#include <stdio.h>
	
	class Foo
	{
	public:
	  ~Foo() { printf("~Foo!\n"); };
	};
	
	int main(void)
	{
	  Foo *foo1 = new Foo[5];
	  Foo *foo2 = new Foo[5];
	
	  printf("delete foo1\n");
	  delete foo1;
	  printf("delete [] foo2\n");
	  delete [] foo2;
	
	  return 0;
	}

In both cases, an array of objects is created.  However, only in the
delete [] case will all the destructors be called.

The obscure part is that some compilers manage this by allocating an
additional bit of memory to keep track of the number of objects in the
array, and free this memory in delete [].  If you call delete instead
of delete[], that memory is never freed and you have a memory leak.

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019