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

问题描述 投票:0回答:2

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

“” HelloHello“

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

“”你好!你好!▌▌▌▌▌▌▌▌▌▌▒“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);
}

c++ arrays pointers char garbage
2个回答
1
投票

您的代码中有多个错误。您分配了错误的内存(char而不是char数组)。您不删除内存。停止使用C字符串,并使用std :: string

#include <iostream>
#include <string>
using std::cout;

void print_array(const char* c)
{
    while (*c) {
        cout << *c;
        ++c;
    }
}

int main()
{
    std::string = "Hello!";
    std::string res = test;
    print_array(test.c_str());
    print_array(res.c_str());
}

1
投票

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

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

当然,可以使用标头std::copy中声明的标准C函数strcpy代替标准算法<cstring>。>>

strcpy( result, s );

并且不要忘记删除分配的数组。

char* res = mystrdup(test);
//…
delete [] res;
© www.soinside.com 2019 - 2024. All rights reserved.