Unsafe C++ memory allocation with new operator

From: Serassio Guido <guido.serassio@dont-contact.us>
Date: Sat, 08 Jan 2005 19:06:46 +0100

Hi,

I have found that the current C++ memory allocation with the new operator
sometimes could be not safe:

Currently memory allocation is done using xmalloc(), see include/SquidNew.h.

In cache_cf.cc, at line 2495, there is this allocation:

     *settings = new RemovalPolicySettings;
     parse_string(&(*settings)->type);
     parse_wordlist(&(*settings)->args);

before latest Robert's changes was:

     *settings = static_cast<RemovalPolicySettings *>(xcalloc(1,
sizeof(**settings)));
     parse_string(&(*settings)->type);
     parse_wordlist(&(*settings)->args);

On Linux this change works fine, but on Windows, and may be on other
platforms, Squid crashes when parsing squid.conf because the memory used is
not set to zero like on Linux.

This is a correct behaviour: xmalloc() don't set to zero the allocated memory.

I don't know if there are other similar code sections, but I think that
using xmalloc() could be dangerous, and the use of xcalloc() should be more
safe.

I'm testing the following changes on the nt branch:

Index: SquidNew.h
===================================================================
RCS file: /cvsroot/squid/squid3/include/SquidNew.h,v
retrieving revision 1.1.2.1
diff -u -p -r1.1.2.1 SquidNew.h
--- SquidNew.h 8 Jul 2003 16:57:51 -0000 1.1.2.1
+++ SquidNew.h 8 Jan 2005 18:01:04 -0000
@@ -43,7 +43,7 @@
  #include <new>
  _SQUID_EXTERNNEW_ void *operator new(size_t size) throw (std::bad_alloc)
  {
- return xmalloc(size);
+ return xcalloc(size, 1);
  }
  _SQUID_EXTERNNEW_ void operator delete (void *address) throw()
  {
@@ -51,7 +51,7 @@ _SQUID_EXTERNNEW_ void operator delete (
  }
  _SQUID_EXTERNNEW_ void *operator new[] (size_t size) throw (std::bad_alloc)
  {
- return xmalloc(size);
+ return xcalloc(size, 1);
  }
  _SQUID_EXTERNNEW_ void operator delete[] (void *address) throw()
  {

What is your opinion about this ?

Regards

Guido

-
========================================================
Guido Serassio
Acme Consulting S.r.l. - Microsoft Certified Partner
Via Gorizia, 69 10136 - Torino - ITALY
Tel. : +39.011.3249426 Fax. : +39.011.3293665
Email: guido.serassio@acmeconsulting.it
WWW: http://www.acmeconsulting.it/
Received on Sat Jan 08 2005 - 11:07:13 MST

This archive was generated by hypermail pre-2.1.9 : Tue Feb 01 2005 - 12:00:02 MST