0
  char  *strncpy(char *dest, char *src, unsigned int n)
{
    unsigned int a;
    a = 0;
    while (src[a] && a < n)
    {
        dest[a] = src[a];
        a++;
    }
    while (a < n)//if src not bigger than n should I put '\0' at the end of dest ?
    {
        dest[a] = '\0';
        a++;
    }
    dest[a] = '\0';
    return (dest);
}

Hello Stackoverflow

I am looking for my mistake, I know that when n > strlen(dest), it does abort on the real strncpy and I am wondering why it is wrong ? Thanks for your help

Patrick Resal
  • 115
  • 2
  • 11
  • 1
    If you are making a function that works like `strncpy`, you must also build in its flaws. See for example [Why is strncpy insecure?](https://stackoverflow.com/questions/869883/why-is-strncpy-insecure) and [Why are strlcpy and strlcat considered insecure?](https://stackoverflow.com/questions/2114896/why-are-strlcpy-and-strlcat-considered-insecure). The key here is to realize that `strncpy` was added to the standard mostly by mistake, it was originally never intended to be used for null terminated C strings. – Lundin Aug 31 '18 at 09:43
  • @Louis Aspas - May you please rephrase your question. This code seems fine but am facing difficulty in understanding question that follows this code – Rizwan Aug 31 '18 at 09:56
  • 1
    Your final `dest[a] = '\0';` is equivalent to `dest[n] = '\0';` which writes beyond the assumed buffer size `n` .. The real `strncpy() would only touch `n` characters. [NOTE: the real `strncpy()` is almost useless] – joop Aug 31 '18 at 10:12

1 Answers1

0

You no need to append '\0' continuously, if you want to rest of the memory of dest to be filled with zeros you can use calloc() while allocating memory

char  *strnncpy(char *dest, char *src, unsigned int n)
{
    unsigned int a;
    a = 0;
    while ( src[a] && a < n)
    {
        dest[a] = src[a];
        a++;
    }
    dest[a] = '\0';
    return (dest);
}
satyaGolladi
  • 180
  • 13