sábado, 5 de dezembro de 2009

Take the whole input to one single string (or explode the memory of your box)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define EXIERR(n,str) fprintf(stderr, str "\n");exit n

void *
xrealloc (void *ptr, size_t size)
{
 void *value = realloc (ptr, size);
 if (value == 0)
  EXIERR(-1, "Can't xrealloc");
 return value;
}

char *
readinput (void)
{
 char *str, buf[10];
 int nbytes;
 str = NULL;
 nbytes = read(0, buf, 10);
 if (nbytes == -1)
    EXIERR(-1, "Error while trying to read from input");
 str = xrealloc (str, nbytes);
 strncpy (str, buf, nbytes);
 if (nbytes < 10) {
  /* chop the new line char */
  str[nbytes - 1] = 0;
  return str;
 }

 while ((nbytes = read (0, buf, 10)) > 0) {
  str = xrealloc (str, 
    (strlen (str) + nbytes ));
  strncat (str, buf, nbytes);
 }
 if (nbytes == -1)
    EXIERR(-1, "Error while trying to read from input");
 /* 
  * the last char is a new line 
  * chop it 
 */
 str[ strlen (str) -1 ] = 0; 
 return str;
}

int 
main (void)
{
 char *str;
 str = readinput();
 puts (str);
 free (str);
 return 0;
}  

The algorithm is:
read from input 
put the bytes in buf
allocate first nbytes to str
copy buf to str
if nbytes < 10
 end str with 0
 return str
else

read from input
 put the bytes in buf
 allocate more nbytes to str
 concatenate buf in str

if there is no more input 
 end str with 0
 return str

cheers (:

It's me again editing...

Some times this program crashes when the sorce file is passed as input.. like
$ ./a.out < source_file.c

raises a two free() error

Nenhum comentário:

Postar um comentário