Own strncpy() C++

Own strncpy() C++

本文关键字:C++ strncpy Own      更新时间:2023-10-16

我正在尝试实现我自己的strncpy()版本,我从这个链接找到了源代码。

但是每次代码到达这个代码while((x++ < n) && (*dest++ = *source++));时,我都会遇到Unhandled exception at 0x00411ad5 in exercise 2.exe: 0xC0000005: Access violation writing location 0x00417800.

下面是完整的代码:

char *strncpy(char * destination, const char * source, size_t n){
        char *dest;
        dest = destination;
        size_t x=0;
        while((x++ < n) && (*dest++  = *source++)); //this is where unhandled exception occurs
        while(x++ < n){
            *dest++ = 0;
        }
        return dest;
    }
int main(){
    char *sample = "blue";
    char * sample2 = "red";
    cout << strncpy(sample, sample2, 5);
    getch();
    return 0;
}

请告诉我为什么会发生这种情况,我应该如何解决它?谢谢!

您的目的地是"blue",这是一个字符串字面量,这是一个常量。因此,它位于内存的只读部分(并由本地sample变量指向),因此写入时会出错。

试试这个:

int main(){
    char sample[] = "blue";
    char * sample2 = "red";
    cout << strncpy(sample, sample2, 5);
    getch();
    return 0;
}

使sample成为本地可写内存中的数组。

不能写入字符串常量(sample);改为写入char数组:

int main(){
    char *sample = "blue";
    char buffer[5];
    cout << strncpy(buffer, sample, sizeof(buffer));
    getch();
    return 0;
}

首先,已经向您解释过,您不能覆盖这样定义的字符串。
其次,你不能使用count <<如果该函数返回指向复制字符串末尾的指针,则使用Strncpy

你的程序有两个主要问题第一个是函数strncpy必须返回destination而不是dest

char *strncpy(char * destination, const char * source, size_t n){
        char *dest;
        dest = destination;
        size_t x=0;
        while((x++ < n) && (*dest++  = *source++)); //this is where unhandled exception occurs
        while(x++ < n){
            *dest++ = 0;
        }
//        return dest;
        return destination;
    }

第二个是字符串字面值是不可变的。任何修改字符串字面值的尝试都会导致未定义的行为。

因此main函数应该按照如下方式重写

int main(){
    char sample[] = "blue";
    char * sample2 = "red";
    cout << strncpy(sample, sample2, sizeof( sample ) );
    getch();
    return 0;
}

另外,使用名称为x的变量作为计数是一种糟糕的编程风格。例如,最好使用i

我会把这个函数写得更简单

char * strncpy( char *destination, const char *source, size_t n )
{
        char *dest = destination;
        while ( n-- && ( *dest++  = *source++ ) );
        while ( n-- ) *dest++ = '';
        return destination;
}