c++ - 为什么我的char *复印机返回不同的东西?

标签 c++ pointers copy c-strings garbage

编写一个简单的字符串复印机并在main()功能中对其进行测试。奇怪的是有时程序会返回

“你好你好”

像它应该的那样,但是也许我每第三次运行它,该程序就会输出:

“你好!你好!▌▌▌▌▌▌▌▌▌▌▒”UòB╚“

为什么有时仅将垃圾数据的尾部添加到第二个字符串的末尾?

#include <iostream>
using namespace std;

int strlength(const char* c)
{
    int size = 0;
    while (*c) {
        ++c;
        ++size;
    }
    return size;
}

char* mystrdup(const char* c)
{
    int size = strlength(c);
    char* result = new char;
    copy(c, c + size, result);
    return result;      
}

void print_array(const char* c)
{
    int size = strlength(c);
    while (*c) {
        cout << *c;
        ++c;
    }
}

int main()
{
    char test[] = "Hello!";
    char* res = mystrdup(test);
    print_array(test);
    print_array(res);
}

最佳答案

该程序具有未定义的行为,因为您没有为结果字符串分配足够的内存。

char* mystrdup(const char* c)
{
    int size = strlength(c);
    char* result = new char;
    ^^^^^^^^^^^^^^^^^^^^^^^           
    copy(c, c + size, result);
    return result;      
}

此外,您没有将终止零复制到结果字符串。

至少两个函数strlengthmystrdup可以如下所示
size_t strlength( const char *s )
{
    size_t size = 0;

    while ( s[size] ) ++size;

    return size;
}

char * mystrdup( const char *s )
{
    size_t size = strlength( s ) + 1;

    char *result = new char[size];

    copy( s, s + size, result );

    return result;      
}

当然,可以使用 header std::copy中声明的标准C函数strcpy代替标准算法<cstring>
strcpy( result, s );

并且不要忘记删除分配的数组。
char* res = mystrdup(test);
//…
delete [] res;

请注意,函数print_array不使用变量size。无需逐字符输出C字符串。

该功能可以像
std::ostream & print_array( const char *s, std::ostream &os = std::cout )
{
    return os << s;
}

最后,标识符c通常与char类型的单个对象一起使用。如果处理字符串,则最好使用标识符s

关于c++ - 为什么我的char *复印机返回不同的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59795197/

相关文章:

c - 指针的内存分配

python - 为什么 python 的字典迭代似乎与副本一起工作?

mysql - MYSQL使用存储过程将一个表的内容复制到另一个表

c - 将数组元素传递给c中的函数

c++ - 将函数指针作为参数传递,其中函数指针的参数是函数的函数指针参数的子参数

python - 在 Python 中复制对象?

c++ - 防止 move unique_ptr C++11

c++ - .cu 源文件中默认包含哪些 header ?

c++ - double&(不通过引用传递)C++

c++ - 获取 QGuiApplication 的小部件列表