Search code examples
cstringcopyreadlinerealloc

How do you add a newline to the end of a string in C?


I am using the editline library to get user input and hand that input to a scanner. The scanner requires any valid input to end with a newline character to unambiguously indicate the end of the last token. However, the input returned by the readline function doesn't end with a newline character.

What is the best way to now add a (newline) character to the end of the string buffer which is not large enough?

The first and the most simple solution I came up with was this:

char* input = readline("> ");
if (!input) { ... }
size_t len = strlen(input) + 2;  // Additional space for newline and null-terminator.
input = (char*) realloc (input, len);
input[len - 2] = '\n';  // Overwrites original '\0'
input[len - 1] = '\0';

Since this is part of a REPL performance isn't too important here so this should work fine. Still, I think this might end up copying lots of data if input cannot simply be extended in memory by realloc. Is there a more clever way to do this or is this one of the problems where we simply have to do some copying?


Solution

  • If there's no space for one more character, there's no space; nothing you can do but copy to a larger memory area.

    Implementation-wise, you could replace your explicit setting of characters with strcat, but as you already know the length of the string, that would be less perfarmant (potentially; I bet modern compilers can optimize the hell out of that).