Subject: Re: Possible bug relating to malloc()/realloc(), popen(), and read()
To: Vincent Stemen <netbsd@crel.us>
From: Roland C. Dowdeswell <elric@imrryr.org>
List: port-i386
Date: 12/02/2004 10:49:28
On 1101949540 seconds since the Beginning of the UNIX epoch
Vincent Stemen wrote:
>

>  while ((count = read(cmd_fd, bufp, block_size)) > 0)
>      {
>      bytes_read += count; 
>      printf("*** Read %i bytes ***\n", count); // debug xxxx
>
>      if (count == block_size)

This conditional is not broad enough.  If you get a short read back
from the pipe, then you will not attempt to realloc(3).  That is,
if we assume that you have a block_size of 2048 and read returns
[1024, 2048, 2048, 2048 ...]:

	read(cmd_fd, bufp, 2048) = 1024;
	bytes_read += 1024;			so it's 1024
	conditional fails---no realloc, no incrementing,
	read(cmd_fd, bufp, 2048) ...

Basically, you need to ensure that your buffer is at least bytes_read
+ block_size at all times, not only when you read an entire buffer.

>          {
>          if ((bufp = realloc(output, bytes_read + block_size)) == NULL)
>              {
>              warn("Could not allocate memory");
>              output[bytes_read] = 0;
>              return(-1);
>              }
>          output = bufp;
>          bufp += bytes_read;

You need to increment bufp outside the if (count == blocksize).
(Obviously in a different way...)

>          }          
>
>      printf("---------------------------------------------\n"); // debug xxxx
>      printf("%s\n\n", output); // debug xxxx
>      }

Not that this will solve your problem nec., but it is probably a
good idea to have the test program be bug free.

--
    Roland Dowdeswell                      http://www.Imrryr.ORG/~elric/