[erlang-questions] Bug in trapexit article "How to use ei ..."

Serge Aleynikov saleyn@REDACTED
Mon Nov 17 04:39:27 CET 2008


Thanks for pointing it out.  This code was more-or-less a quick&dirty 
copy/paste from 
http://www.erlang.org/doc/tutorial/erl_interface.html#5.2 that suffers 
from a buffer overrun issue.  I posted the corrections that you found.

Serge

Mikl Kurkov wrote:
> It seems that the code in the trapexit article
> http://www.trapexit.org/How_to_use_ei_to_marshal_binary_terms_in_port_programs
> has some bugs that I ran into.
> In the next code 
> 
> [c]
> int read_cmd(byte *buf, int *size)
> {
>   int len;
> 
>   if (read_exact(buf, 2) != 2)
>     return(-1);
>   len = (buf[0] << 8) | buf[1];
> 
>   if (len > *size) {
>     buf = (byte *) realloc(buf, len);
>     if (buf == NULL)
>       return -1;
>     *size = len;
>   }
>   return read_exact(buf, len);
> }
> [/c]
> 
> if the size of binary data is more than the size of the buffer then data is
> reallocated, but the pointer in the main function doesn't change.
> I think it should be something like this:
> 
> [c]
> int read_cmd(byte **buf_ptr, int *size)
> {
>   int len;
>   char *buf = *buf_ptr;;
>   
>   if (read_exact(buf, 2) != 2)
>       return -1;
> 
>   len = (buf[0] << 8) | buf[1];
> 
>   if (len > *size) {
>     buf = (byte *) realloc(buf, len);
>     if (buf == NULL)
>       return -1;
>     *buf_ptr = buf;
>     *size = len;
>   }
> 
>   return read_exact(buf, len);
> }
> [/c]
> 
> The call of read_cmd in the main function should be changed into 
> [c]
> while (read_cmd(&buf, &size) > 0) {
> [/c]
> 
> Besides the code doesn't work properly in the system with the char defined
> as signed type.
> 
> Hope this information will be helpful for someone.
> --
> Mikl




More information about the erlang-questions mailing list