[Insight-developers] Array Initialization

Samson Timoner samson at bwh . harvard . edu
Wed, 17 Dec 2003 19:37:54 -0500


I've run into an annoyance with array initialization in several classes.

As an example, consider Code/Algorithms/itkHistogramImageToImageMetric.h.
There is an array, DerivativeStepLengthScales, which should have the number
of parameters of a transformation as its length.

However, when the class is instatiated, the transform is unknown so that
the default length of DerivativeStepLengthScales is unknown. Thus, to use
this class, one MUST set DerivativeStepLengthScales. And, if one does not,
there eventually is a seg-fault.

Now, if one looks at the class, one might well suspect that this array does
not need to be initialized. I find this to be true for two reasons:

 1) In the constructor, the array calls the function Fill(1). Thus it
    appears that the array has been set and need not be initialized. In
    fact, since the array has the default length 0, this command does nothing.

 2) There is no note in the class that says: "To use this class, you must
    set DerivativeStepLengthScales".

Several times now, I have found myself chasing down seg-faults which turn
out to be errors on my part assuming that arrays did not need to be
initialized, when in fact they did.

Is there something we can do about this?

  Does it makes sense to get rid of initializations of arrays of length 0?

  Adding a simple note to the header of a class that says "You must set the
  following variables or this class will crash and burn" would be very
  helpful.

  A different way would be to explicitly check for array lengths to make
  sure they are of the correct size. Maybe we only do this while debugging
  is turned on.

In short, I'd like to get rid of the most common way that I cause
seg-faults when using a new class.

 Any thoughts?

-- Samson