[comp.sys.mac.programmer] Help with bad calloc

tarr-michael@CS.YALE.EDU (michael tarr) (09/19/90)

For some reason using THINK C 4.02 the following calloc (at the end of the
code segment) breaks. It returns a pointer that is not really valid (but not
NULL). Here are the data structures used:

struct objects {
  short      theObj;
  Rect      theRect;
  RGBColor    theColor;
  Point      thePen;
  struct objects  *next_object;
};
typedef struct objects objects;

struct picts {
  char*      thePict;
  struct picts  *next_pict;
};
typedef struct picts picts;

struct symbolList {
  char*        theSym;
  objects        *symObj;
  picts        *symPict;
  struct symbolList  *next_symbol;
};
typedef struct symbolList symbolList;

symbolList  *symbols;

objects    *objPtr;
picts    *pictPtr;
symbolList  *symPtr;

/*** OpenSymbolFile ***/

extern void OpenSymbolFile(char*);

void OpenSymbolFile(char* symFile)
{
  FILE*    symfp;
  char    inStr[80], tempStr[30];
  char    graphOp[15];
  RGBColor  penColor = { 0x0000, 0x0000, 0x0000 };
  Point    penDim = { 1 );
    FatalError();
  }
  
  symbols = 0;
  
  while ( fscanf(symfp, "%s", inStr) != EOF ) {
    if (symbols == 0) {

      if ( !ValidPointer( (Ptr) (symbols = (symbolList*) 
            calloc( (size_t) 1, (size_t) sizeof(symbolList) )) ) ) {
          /*^^^^^^ bad calloc -- any ideas? */

        ErrorHandler( "OpenSymbolFile", "Failed calloc for symbolList at:", 
              inStr, FATAL_ALERT );
        FatalError();
      }
      symbols->next_symbol = 0;
      symPtr = symbols;
}

Any ideas?

Mike Tarr

tarr@cs.yale.edu
-- 
 * Mike Tarr                                    The Human Neuron Project  *
 * tarr@cs.yale.edu                             Department of Psychology  *
 * "My opinions are always my own."             Yale University           *
 **************************************************************************

rcfische@polyslo.CalPoly.EDU (Ray Fischer) (09/20/90)

tarr-michael@CS.YALE.EDU (michael tarr) writes ...
>For some reason using THINK C 4.02 the following calloc (at the end of the
>code segment) breaks. It returns a pointer that is not really valid (but not
>NULL). Here are the data structures used:

I've not copied your code in this reply, but nowhere do I see either a
	#include <stdlib.h>
or a 
	void *calloc();

With Think C (and possibly other C compilers) a definition for the calloc (and
alloc, et al) function is required or you will get bad results.

The reason is that the default return value for a function is an int.  In
Think C an int is just 16 bits.  Thus, without any declaration to the contrary,
Think C will take the 32-bit address returned, expand the low-order 16-bits
to 32 bits, then assign that value to your pointer.  

The solution is simply to tell the compiler that calloc returns a 32-bit result.

Ray Fischer
rcfische@polyslo.calpoly.edu