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|||||.....

4
  • 1
    Why not use strcat ? Commented Jan 20, 2016 at 5:58
  • what's your concern about utf-8? Commented Jan 20, 2016 at 6:20
  • Actually I was confused. I'm concerned of situations where text+1 is not equal to text[1]. Commented Jan 20, 2016 at 8: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. Better and safer alternatives are memcpy and strcpy (with buffer size known/checked). Commented Jan 20, 2016 at 10:04

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

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?
Please add a note to your solution that a caller function is then responsible for freeing the memory allocated by concat after use.
Yes, strcat simplifies the task – but it does no size testing and can overflow the destination array, as opposite to the OP's approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.