Parse a contrived message protocol with first byte data length followed by data
Below is an alternative example of how messages could be extracted.  Instead of a state machine with saved-state inside your splitmessages function, I have moved the saved-state out of the function into a structure that is passed-in.   I have also checked for unexpected data at the start of the function.  The return value is 0 on failure or the number of bytes consumed from the input stream on success.  I didn't check for size bytes occurring in the wrong place - replace the memcpy with a function that checks the bytes copied for that.

Note that your protocol has to distinguish between data bytes and size bytes. I have arbitrarily made the boundary 32, the first printable char.

#include &lt;string.h&gt;
#include &lt;assert.h&gt;

#define DATA_MIN_VALUE 32
#define DATA_MAX_SIZE  (DATA_MIN_VALUE)

struct message {
    size_t size;
    size_t remaining;
    char data[DATA_MAX_SIZE];
};  
typedef struct message Message;

static inline size_t min(size_t a, size_t b)
{
    return a &lt; b ? a : b;
}

static inline int is_data(unsigned char ch)
{
    return  ch &gt;= DATA_MIN_VALUE;
}

static size_t
get_message(Message *msg, const unsigned char *bstream, size_t length)
{
    size_t len;
    assert(length);

    if ((msg-&gt;remaining == 0) &amp;&amp; is_data(bstream[0])) {
        /* Data instead of message; caller must handle - eg. discard data up
         * to next message */
        return 0;
    }

    if (is_data(bstream[0])) {
        msg-&gt;size = 0;
        msg-&gt;remaining = bstream[0];
    }

    len = min(length-1, msg-&gt;remaining);

    memcpy(&amp;msg-&gt;data[msg-&gt;size], &amp;bstream[1], len);
    msg-&gt;size += len;
    msg-&gt;remaining -= len;

    return len + 1;
}


The code should compile but is untested.  Hope it helps to have another perspective.