-3

Code that copies the text from source to destination and then prints it as a buffer

void strcpy(char *destination, char *source, int bufferSize) { 
    int i = 0;
    while (i < bufferSize && *source != 0) { 
        *destination = *source;  
        destination += 1;
        source += 1;
        i += 1;
    }

    *destination = 0;
}
char *text = "Tomek";
char buffer[1024];

strcpy(buffer, text, 1024);
Marika
  • 1
  • 1
  • 2
    If the source c style string is too long. the `*destination = 0;` will be a buffer overflow as it writes one past the end. – Avi Berger May 24 '23 at 03:28
  • 3
    don't use c-style strings in c++ please – sp2danny May 24 '23 at 03:39
  • While the OP has tagged C++, this is entirely C concepts. Also, `source` should be `const char *`. – Chris May 24 '23 at 03:51
  • 1
    @Chris there are still people who believe that the best way to learn C++ is to start with C. The more those languages diverge, the less true that becomes. – Mark Ransom May 24 '23 at 23:21

1 Answers1

0

It seems likely you want strncpy which does approximately this.

From cppreference.com page on strncpy:

  1. Copies at most count characters of the character array pointed to by src (including the terminating null character, but not any of the characters that follow the null character) to character array pointed to by dest.

For fun, consider the following definition of your function, renamed slightly. Do you understand what's going on with the pointers?

void strcpy_(char *dest, const char *src, size_t buf_size) {
    buf_size--;
    while (buf_size-- && *src && (*dest++ = *src++));
    *dest = '\0';
}
Chris
  • 26,361
  • 5
  • 21
  • 42
  • 1
    actually strlcpy. Using strncpy for this is actually a common cause of bugs because strncpy does not null-terminate the output. – user253751 May 24 '23 at 03:42
  • I just started to learn pointers and I do understand the basics minimum for now. – Marika May 24 '23 at 09:56
  • It's actually interesting how the while loop looks in your code. May I ask why this part of the code is included in a condition instead? `(*dest++ = *src++)` – Marika May 24 '23 at 09:59
  • Taking advantage of the short-circuiting behavior of `&&` and that `(*dest++ = *src++)` will not return `0`. – Chris May 24 '23 at 14:23