Read just one byte with read() function from unistd
11:23 23 Mar 2026

I'm trying to start a hangman project, and first I want to take care of how to get user letter from the terminal, I know I can read just one byte and store that value into a pointer's address with

char *ptr;
int read_bytes;

read_bytes = read(0, ptr, 1);
//NULL checks

but right now I did a function that is returning a NULL terminated buffer with just 2 chars (the user's input and a NULL char at the end).

This is the code.

#include "utils.h"

char    *read_one_byte(int   fd)
{
    char        *buf;
    int     read_bytes;

    if (!(buf = malloc(sizeof(char) * 2)))
    return (NULL);
    if ((read_bytes = read(fd, &buf, 1)))
    {
        buf[1] = '\0';
        return (buf);
    }
    else
        return (NULL);
}

Is it worth it to NULL terminate the buffer even if its content is just one character, or should I not bother at all?

c linux linux-kernel file-handling