Re: Memory allocation problem?

From: Daniel Koepke (dkoepke@CALIFORNIA.COM)
Date: 02/18/98


On Wed, 18 Feb 1998, Cipher wrote:

->   So I added an int array resistances[10] to said struct, removed it
->from its previous struct, and made the necessary change in utils.c.  After
->wiping the pfile (just one player, heh.. me.), I logged on and statted
->myself to see if all was well.  Turned out all my resistance percentages
->were set to 0, except for resistance[5], which was something like
->137198217.  *boggle*  Attempting to set that particular resistance to any
->value (via do_set) crashed the mud, but I could set any other ....

If your above description of what you did isn't omitting any
major steps, then I know one problem with your code right off.
Initialize the values to zero in init_char(), as saving throws
are.  The function is in db.c.  After doing so, wipe your pfile
again and cross your fingers.

->   I'm vaguely aware of things called 'malloc' and 'calloc', but don't
->know if they would solve my problem or how to use them, as I am a
->semi-newbie to C (but not a /complete/ dumbass ;).  Any suggestions?

malloc() and calloc() are C library functions that are used
for dynamic memory allocation, which has nothing to do with
pre-created arrays (e.g., array[10] is pre-created, and cannot
change size).  For example:

  int *dynamic_int_array;

  /* initialize dynamic_int_array to dynamic_int_array[5] */
  dynamic_int_array = (int *) calloc(sizeof(int), 5);
  dynamic_int_array[2] = 1;

  /* free data and allocate using malloc() */
  free(dynamic_int_array);
  dynamic_int_array = (int *) malloc(sizeof(int)*5);
  dynamic_int_array[2] = 1;

  /* resize dynamic_int_array[5] to dynamic_int_array[10] */
  dynamic_int_array = realloc(dynamic_int_array, sizeof(int)*10);
  dynamic_int_array[9] = 1;

The allocation is performed while the program is running, so
prior to that point in the code, dynamic_int_array was not
taking up memory (this is admittedly an over-simplification
and not 100% true; but I'm not writing this to be concise,
only clear).  The only differences between malloc() and
calloc() are (a) calloc takes a second parameter, even
though the behaviour is easily simulated with malloc()
(e.g., calloc(sizeof(int), 5) initializes an array of 5
integers; malloc(sizeof(int)*5) does the same), (b) calloc()
initializes each element of the array to 0 (which is probably
why it has the second paramter seperate), malloc() leaves it
uninitialized (same as the compiler when dealing with
pre-defined arrays/variables).

-dak


     +------------------------------------------------------------+
     | Ensure that you have read the CircleMUD Mailing List FAQ:  |
     | http://democracy.queensu.ca/~fletcher/Circle/list-faq.html |
     +------------------------------------------------------------+



This archive was generated by hypermail 2b30 : 12/15/00 PST