0

If i want to concatenate 2 strings in C, do i have to allocate an extra null char for every string or one is enough?

int main(){
    char *s1 = NULL;
    char *s2 = NULL;
    char *s1_s2 = NULL;

    s1 = malloc(sizeof(char) * strlen("string1") + 1);
    strcpy(s1, "string1");
    s2 = malloc(sizeof(char) * strlen("string2") + 1);
    strcpy(s2, "string2");

    s1_s2 = malloc(sizeof(char) * (strlen(s1) + strlen(s2)) + 2); // shouldn't it be only 1 null char ?
    strcpy(s1_s2, s1);
    strcat(s1_s2, s2);
}

in this question, they use 2 null bytes for each string. Can some one shed some light? Thanks

Community
  • 1
  • 1
Vlad Balmos
  • 3,372
  • 19
  • 34

5 Answers5

3

No, you don't need two extra null bytes.

In memory, your strings will look like:

s1 -> 's' 't' 'r' 'i' 'n' 'g' '1' '\0'

s2 -> 's' 't' 'r' 'i' 'n' 'g' '2' '\0'

s1_s2 -> 's' 't' 'r' 'i' 'n' 'g' '1' 's' 't' 'r' 'i' 'n' 'g' '2' '\0'
Renan Greinert
  • 3,376
  • 3
  • 19
  • 29
2

Only one is needed.

In the question you linked, they are actually also adding an extra space character which requires an extra byte.

Vadim
  • 4,996
  • 1
  • 26
  • 30
1

The final string should end with a null byte so one is enough.

Edit: The question you sent, there's a space between the two strings.

strcpy(both, first);
strcat(both, " ");
strcat(both, second);
iabdalkader
  • 17,009
  • 4
  • 47
  • 74
1

Only one is needed. You always need just one null character at the end of the string, which here happens to be a concatenation of two strings.

leif
  • 1,987
  • 4
  • 19
  • 22
1

In the question that you linked to, a space is put between the strings that are concatenated together. An extra char must be allocated for this space.

In your example, you do not put a space between the strings, so only one additional char is needed.

Mankarse
  • 39,818
  • 11
  • 97
  • 141