Except in special cases, you don't need to write that yourself. If—in the end—you just want to read a line, the libraries and consoles provide line editing features to the user. All you need to do is take in the line of text.
This does require memory management, though. In C, a block of memory assigned from the heap must be returned to the heap—exactly once! It is useful to have the concept of single ownership and understand when ownership is passed back and forth. Some functions will allocate a block and transfer ownership of it to the caller. The caller must free the block when done with it (or pass ownership along). There is no bookkeeping on who the owner is; It is just convention and documentation.
As an aside, although both C and C++ give you enough rope to hang yourself, C++ might be a better language to learn for general programming because with C it is much easier to shoot yourself in the foot.
The getline function
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
If *lineptr
is set to NULL
and *n
is set 0 before the call, then
getline()
will allocate a buffer for storing the line. This buffer
should be freed by the user program even if getline()
failed.
Alternatively, before calling getline()
, *lineptr
can contain a
pointer to a malloc()
-allocated buffer *n
bytes in size. If the
buffer is not large enough to hold the line, getline()
resizes it
with realloc()
, updating *lineptr
and *n
as necessary.
In either case, on a successful call, *lineptr
and *n
will be updated
reflect the buffer address and allocated size respectively.
—http://man7.org/linux/man-pages/man3/getdelim.3.html
So in this case, the caller transfers ownership of one buffer to the function and the function transfers back ownership of the same or another buffer. (realloc()
is the same.)
char *line = NULL;
size_t len = 0;
ssize_t read;
read = getline(&line, &len, stdin));
if (read != -1) {
// use line in this block
}
free(line); // don't use line after this point
See http://man7.org/linux/man-pages/man3/getdelim.3.html for a longer example that includes calling getline()
to get line after line.