Re: Unsafe C++ memory allocation with new operator

From: Henrik Nordstrom <hno@dont-contact.us>
Date: Sat, 8 Jan 2005 23:18:02 +0100 (CET)

On Sat, 8 Jan 2005, Serassio Guido wrote:

>> From my understanding of C++ the new operator is not supposed to guarantee
>> the memory is cleared. This is the job of the constructor and related
>> member initializers, where the default constructor memsets the object to 0.
>
> So, in the Robert's patch something should be wrong: he changed a xcalloc()
> call with a new operator.

No, I stand slightly corrected, there is no automatic default constructor
in C++. Just like in C if you do not explicity initialize allocated memory
you get garbage.

There is nothing wrong with the patch. What is wrong is the
RemovalPolicySettings class which does not have a constructor and leaves
the object uninitialized. This then crashes when parsing as the parsing
routines tries to free the old values (garbage).

The following should fix it:

Index: src/structs.h
===================================================================
RCS file: /cvsroot/squid/squid3/src/structs.h,v
retrieving revision 1.504
diff -u -p -r1.504 structs.h
--- src/structs.h 3 Jan 2005 16:08:26 -0000 1.504
+++ src/structs.h 8 Jan 2005 22:08:42 -0000
@@ -213,6 +213,8 @@ class RemovalPolicySettings
  public:
      char *type;
      wordlist *args;
+
+ RemovalPolicySettings() type(NULL), args(NULL) {};
  };

  class external_acl;

And here follows a silly example demonstrating that there is no default
constructor to save your feets when you forget to declare one:

#include <iostream>
#include <string.h>

class Dummy {
public:
     char text[128];
};

int main(int argc, char **argv)
{
     Dummy *p;
     char *s;

     s = new char[128];

     strcpy(s, "Hello");

     delete s;

     p = new Dummy;

     std::cout << p->text << std::endl;
}

Regards
Henrik
Received on Sat Jan 08 2005 - 15:18:07 MST

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