1

I am doing this to append some text:

char text[100];
strcpy(text, "Hello");

char input[] = "random";
strncpy(text + strlen(text), input, sizeof(text) - strlen(text));

I did this and it seems to work fine for ASCII text. But I fear I am not being safe doing pointer arithmetic. What if the input is UTF-8?

FYI, when I do text + strlen(text) I am getting a pointer to the end of the sentence and then appending to the end of the sentence.

i.e.

text => |h|e|l|l|o|NUL||||||....

text + strlen(text) => |NUL|||||.....

SKD
  • 464
  • 1
  • 4
  • 16
alex murphy
  • 43
  • 1
  • 4
  • 1
    Why not use `strcat` ? – ameyCU Jan 20 '16 at 05:58
  • what's your concern about utf-8? – Sam Liao Jan 20 '16 at 06:20
  • Actually I was confused. I'm concerned of situations where ``text+1`` is not equal to text[1]. – alex murphy Jan 20 '16 at 08:35
  • In general, you should avoid `strncpy`, it is a [dangerous and unsafe function only ever intended to be used for anything but ancient string formats in Unix](http://stackoverflow.com/questions/2114896/why-are-strlcpy-and-strlcat-considered-insecure). Better and safer alternatives are `memcpy` and `strcpy` (with buffer size known/checked). – Lundin Jan 20 '16 at 10:04

1 Answers1

2

This is exactly why strcat exists:

char text[100];
strcpy(text, "Hello");

char input[] = "random";
strcat(text, input);

To ensure memory sensitive concatenation preventing overflow, please use the following amendment:

   char *text;

   //allocate memory
   text = (char *) malloc(15);
   strcpy(text, "Hello");


   char input[] = "random";

   //reallocate memory
   text = (char *) realloc(text, strlen(text)+strlen(input) +1);
   strcat(text, input);
   free(text);
Spade
  • 2,220
  • 1
  • 19
  • 29
  • What if the ``text`` buffer isn't large enough. And if I use ``strncat`` I still need to calculate how much empty space is left over in ``text`` right? – alex murphy Jan 20 '16 at 06:14
  • 1
    Please add a note to your solution that a caller function is then responsible for freeing the memory allocated by `concat` after use. – CiaPan Jan 20 '16 at 06:29
  • Yes, `strcat` simplifies the task – but it does no size testing and can overflow the destination array, as opposite to the OP's approach. – CiaPan Jan 20 '16 at 06:34