delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/08/05/13:30:26

From: brunobg AT geocities DOT com (Bruno Barberi Gnecco)
Newsgroups: comp.os.msdos.djgpp,comp.lang.c
Subject: Realloc()ing data of a node from a linked list
Date: 5 Aug 1998 12:24:03 -0500
Organization: Newscene Public Access Usenet News Service (http://www.newscene.com/)
Lines: 46
Message-ID: <35c89230.2078137@news3.newscene.com>
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

I'm writing a function that inserts a character in the data of a node like:
struct node {
     struct node *next, *previous;
     unsigned char * data;
}
The function I wrote is (dl_strlen is just strlen(pointers.current->data):
void dl_insert_char ( unsigned char newdata, int n, BOOLEAN insert ) {
    int i, size, length = dl_strlen();
    if ( insert == TRUE ) {
      if ( n >= length )         size = n + 1;
      else                       size = length + 1;
      if ( realloc ( pointers.current->data, size ) == NULL ) {
        alert("Could not allocate memory at dl_insert_char");
        return;
      }
      else {
        if ( n < length ) {
          for ( i = length; i > n; i-- )
            pointers.current->data[i] = pointers.current->data[i-1];
        }
        else {
          for ( i = length; i < n; i++ )
            pointers.current->data[i] = 32;
        }
      }
    }
    else {
      if ( n >= length ) {
        if ( realloc ( pointers.current->data, n + 1 ) == NULL ) {
          alert("Could not allocate memory at dl_insert_char");
          return;
        }
        for ( i = length+1; i < n; i++ )
          pointers.current->data[i] = 32;
      }
    }
    pointers.current->data[n] = newdata;
}
Where pointers.current is a pointer to the node I'm using. This function works
about 3/5 of the time, but sometimes it just goes mad after the last line, and if
string that was "Stri", the new character being 'n', the result is
"Stri\030t\120\093"; garbage. What's wrong?

"There's never enough time to do all the nothing you want" Bill Watterson 
Bruno Barberi Gnecco <brunobg AT geocities DOT com> ICQ #1383173 - PGP 5.0i user 
My other OS is Linux -=- http://graphx.home.ml.org -=- Electric Eng, Poli

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019