Thursday, June 29, 2023

Horror Code: ToString Overflow

 This article was originally posted on JRoller on June 12, 2013

A colleague of mine showed me this code from one of the libraries we are using:

    @Override
    public String toString()
    {
        final boolean reuse = false;
        try
        {
            this.ssc.socket().getReuseAddress();
        }
        catch (SocketException exception)
        {
            LOGGER.error(this+ \" SocketException\", exception);
        }

        return String.format(\"AccId[%1$10s] Port[%2$s] reuse=%3$s backlog=%4$s\", hashCode(), this.listenPort, reuse, BACKLOG); 
    } 

The strange part is the code trying to perform some socket operation during a toString. My guess is that they wanted to return something into that poor boolean that just seem stick to a false value. But what does really happen if you get that dreaded SocketException? Do you see it? Yes, that’s a Stack Overflow!

For those who did not see it at the time, here is the reason 10 years later: the logging of (this + something) will cause a call to the same toString method.

No comments:

Post a Comment