Used uninitialized in this function

Posted by Zeno on Sat 06 Dec 2003 03:09 AM — 5 posts, 14,106 views.

USA #0
I seem to have encountered a problem, and I cannot think of why its doing this. The error is:


commands.c:223: warning: `dsock' might be used uninitialized in this function


Now, the dsock is defined. (As this)

D_SOCKET *dsock;


Without it, it would get a undefinded error. With it, the function crashes the MUD. Here is the full function:

void cmd_score(D_MOBILE *dMob, char *arg)
{
  BUFFER *buf = buffer_new(MAX_BUFFER);
  D_SOCKET *dsock;

   bprintf(buf, "#c- - - = = = Score = = = - - -#n\n\r" );
   bprintf(buf, "#CName: %s\n\rKills: %d\n\rDeaths: (null)\n\r", dMob->name, dMob->kills);
   bprintf(buf, "#CHost: %s\n\r", dsock->hostname );
   if ( dMob->level == 4 )
    bprintf(buf, "#CRank: Owner\n\r" );
   else if ( dMob->level == 3 )
    bprintf(buf, "#CRank: Admin\n\r" );
   else if ( dMob->level == 2 )
    bprintf(buf, "#CRank: Player\n\r" );
   else if ( dMob->level == 1 )
    bprintf(buf, "#CRank: Guest\n\r" );

   bprintf(buf, "#c- - - = = = = = = = = = - - -\n\r#n" );
  text_to_mobile(dMob, buf->data);
  buffer_free(buf);
}


What is this uninitialized problem doing, and how do I correct it?
USA #1
That's what's called "dereferencing" an undefined pointer.

Your pointer, dsock, is not initialized, and therefore defaults to whatever was in the memory block it was assigned to. 99.99999% of the time, that is total giberish.

You're using dsock->hostname without assigning it a value; that's your error. You need to either have dsock point to something valid, or not have it there at all - including places where you use it.
USA #2
I've gotten it to work other places, such as this:

void cmd_who(D_MOBILE *dMob, char *arg)
{
  D_MOBILE *xMob;
  D_SOCKET *dsock;
  BUFFER *buf = buffer_new(MAX_BUFFER);

  bprintf(buf, " - - - - ----==== Who's Online ====---- - - - -\n\r");
  for (dsock = dsock_list; dsock; dsock = dsock->next)
  {
    if (dsock->state != STATE_PLAYING) continue;
    if ((xMob = dsock->player) == NULL) continue;

    bprintf(buf, " %-12s   %s\n\r", xMob->name, dsock->hostname);
  }
  bprintf(buf, " - - - - ----======================---- - - - -\n\r");
  text_to_mobile(dMob, buf->data);
  buffer_free(buf);
}


What makes this work, and not the first one?
USA #3
Well, before this line:
if (dsock->state != STATE_PLAYING) continue;

You have this line:
for (dsock = dsock_list; dsock; dsock = dsock->next)

Which "initializes" the variable dsock to dsock_list.

Imagine the following code:
int i;
printf("Hello! My number is %d.", i);


What would you expect this to do? What value would i have? It's the same problem with pointers, and arguably even more so. Before you access a what the pointer points to, it has to point to something real.
USA #4
Oh, no wonder. I am thinking that dsock is defined as the person who typed the command... I have to look up how to make it define that then...