Problem 776 - Use of G4Allocator causes problems in derived classes
Summary: Use of G4Allocator causes problems in derived classes
Status: RESOLVED WORKSFORME
Alias: None
Product: Geant4
Classification: Unclassified
Component: tracking (show other problems)
Version: 7.1
Hardware: PC Linux
: P2 normal
Assignee: Makoto.Asai
URL:
Depends on:
Blocks:
 
Reported: 2005-08-01 22:39 CEST by Tom Roberts
Modified: 2005-09-30 18:39 CEST (History)
0 users

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this problem.
Description Tom Roberts 2005-08-01 22:39:02 CEST
All classes that use G4Allocator<Type> should check in operator new
that the size of the allocation is equal to sizeof(Type). This will
prevent difficult-to-debug segmentation faults in constructors of
classes derived from classes that use G4Allocator. This subtle point
should also be commented in the source of all such classes.

I suggest something like this:
inline void* G4Trajectory::operator new(size_t nbytes)
{
  // G4Allocator<G4Trajectory> only allocates objects of that size
  // derived classes _must_ provide their own operators new and delete
  assert(nbytes == sizeof(G4Trajectory));
  void* aTrajectory = (void*)aTrajectoryAllocator.MallocSingle();
  return aTrajectory;
}


G4Trajectory caused me great pain until I figured this out.
Comment 1 Tom Roberts 2005-09-30 18:39:59 CEST
This can "work for you", and yet still be a ticking time bomb for all users.

To test it, you must add at least (malloc quantization [=8?]) bytes of new data
to the class, and must actually use the new data in an allocated object,
which is then deleted. This must happen many times to really test it. If, for
example, you only added 4 bytes to the object, but the original class happened
to have >= 4 bytes unused in the quantization, it would just happen to work
for you, and yet cause problems for others.

I _STRONGLY_ urge that all uses of G4Allocator be modified as I
suggested (to test the size of the object being allocated), and the
documentation updated. This is a ticking time bomb that can cause
unexplained segmentation faults ANYWHERE in the program, because
the heap gets corrupted.

I _KNOW_ this caused me considerable pain, and I'll bet many others.