Re: Memory allocation troubles- i think

From: Patrick Dughi (dughi@imaxx.net)
Date: 12/14/00


        > part about making an introduction system snipped <

> struct known_char_node *new_rec_ptr;
>
> I'm currently using this (it compiles correctly but I crash on the specified
> line)
>
>
> void add_friend(struct char_data *ch, struct char_data *victim)
> {
>         struct known_char_node *new_rec_ptr; //Temporary pointer for the new friend
>
>         new_rec_ptr = (struct known_char_node *) malloc((sizeof(struct
> known_char_node)) + 1); //Allocate Memory
>
>         if(new_rec_ptr != NULL)         //Allocated memory correctly?
>         {                               //Get data and insert node
> /*ERROR*/strcpy(new_rec_ptr->known_char, GET_NAME(ch));// ERROR IS
> HERE            insert_node(new_rec_ptr, ch, victim);
>         }
>         else
>         log("SYSERR:  Memory allocation failed in act.comm.c(600)");
> }
>

        Okay.  I'll assume (based on info above) that your known_char_node
struct is the following:

struct known_char_node {
  char *name;
  struct known_char_node *next;
}
        Design issues aside (it'd just be easier to save the idnum, but
only if you're concerned with time, effort, memory, and cpu time
required), you're going to do something like the following each time you
need to add one;

   struct known_char_node *new;

   new = (struct known_char_node *) malloc(sizeof(struct known_char_node));
        /* could malloc the memory on size of GET_NAME() but strdup does
          it for us */
   new->name = strdup(GET_NAME(ch_to_remember));

   new->next = ch_to_save_to->known_chars;
   ch_to_save_to->known_chars = new->next;

        ...


        If you want to check for errors, you can throw that in too, but
frankly, if you're getting out of memory errors, you'll probably crash
anyway. :)

                                        PjD

--
   +---------------------------------------------------------------+
   | FAQ: http://qsilver.queensu.ca/~fletchra/Circle/list-faq.html |
   | Archives: http://post.queensu.ca/listserv/wwwarch/circle.html |
   +---------------------------------------------------------------+



This archive was generated by hypermail 2b30 : 04/11/01 PDT