The condition in while(ret_val == buffer || read_length is wrong. ret_val == buffer will always be true, and if read_length is true when the loop is reached, it will always remain true because read_length is only ever reduced (well, until it underflows INT_MIN).