Re: PR 53255 discussion

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

 



>> So I continue to say it is wrong to close this.  Either the compiler should be
>> giving at least an error for illegal access to the object,

To answer this part more fully.  You could have defined A::operator
new in a separate file, so the compiler can't "know" that you're
really calling it to allocate a different type.

// header A.h

#include <cstddef>
#include <stdlib.h>
typedef unsigned int uint;

class C{ // just here to be faithful to the original code
  int y;
};

class A{
public:
  typedef A this_type;

  void* operator new(size_t enfacia_size, uint count);
  uint count;
};

// header B.h

class B : public C, public A{
public:
    int i;
};

// main.cc

#include "A.h"
#include "B.h"

int main(){
  B *b_pt = new(5) B;
  uint j=0;
  j++;
};


// A.cc

#include "A.h"

  void* A::operator new(size_t enfacia_size, uint count);
  {
      size_t total_size
    = enfacia_size
    + sizeof(int) * count; // the 'tail'
    ;
      this_type *new_pt = (this_type *)malloc(total_size);
      new_pt->count = count;
      return new_pt;
  };

Now it should be clear that when you allocate a B the compiler finds
A::operator new and calls it.  That runs the code which was separately
compiled in A.o, which knows nothing about type B.  The code inside
operator new cannot possibly know how to adjust the new_ptr->count
access to "do the right thing" in the case where the operator new is
called for a B.  All it knows is it was asked to allocate a certain
number of bytes, with a certain "count" argument, it doesn't know if
it was called to allocate a B, or an X, or a Y or a Z.

Whether the function operator new is inline (as in your original code)
or defined in a separate file (as above) should not affect its logic.
The code does the same thing in both cases.

Insisting that the compiler should know you're creating a B and should
fix the code (or notice you're doing something dumb) is not allowed by
the C++ standard.

Insisting the compiler should warn you there's a problem is not
practical.  C++ is not a memory safe language.  If you are going to
muck around with raw memory and low-level features such as allocation
functions you had damn well better know what you're doing, or you will
get hurt.  Tough.  If you can't do it right then don't to it at all.
If you don't understand the C++ object model then for crying out loud
don't mess around with complex low-level memory handling!



[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux