Is it possible to prevent buffer overflow with strcpy in C++ using pointers?

112 views Asked by At

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);
1

There are 1 answers

4
Chris On

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';
}