-4

I'm unable to make strncpy when I want to copy 2 chars from string, but same code is working when I want to copy 3 chars.

In this example, I need strncpy() to store 12 in 'to' variable:

void main(){
    const char* from = "12345678";
    char *to = (char*) malloc(3);
    strncpy(to, from, 2);

    printf("%s", to);
    free(to);
}

but when I use strncpy(to, from, 3) with malloc(4), it works ok. Any solution to make this work?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
ggoran
  • 630
  • 2
  • 12
  • 29
  • 2
    It is difficult to offer solutions when the problem statement is simply, "it doesn't work". Please [edit] your question to give a more complete description of what you expected to happen and how that differs from the actual results. See [ask] for hints on what makes a good explanation. – Toby Speight Jun 30 '17 at 12:30
  • 2
    Just read the doc: No null-character is implicitly appended at the end of destination if source is longer than num. – Boiethios Jun 30 '17 at 12:31
  • 2
    Hint for the future: Don't use `strncpy`, most of the time it does not do what you want. – Jabberwocky Jun 30 '17 at 12:41
  • This bug is caused by using the dangerous `strncpy` function indeed. Never use that function, use `strcpy` or `memcpy` instead (together with appropriate buffer size checks). – Lundin Jun 30 '17 at 14:02

1 Answers1

3

You forgot to append the destination string with a terminating zero.

char *to = (char*) malloc(3);
strncpy(to, from, 2);
to[2] = '\0';
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335