栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ 库函数strcat() 注意事项,申请char数组要记得初始化

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ 库函数strcat() 注意事项,申请char数组要记得初始化

在进行自定的MyString "+"运算符重载函数编写时,遇到问题

void test01()
{
	MyString str1 = MyString("jack");
	MyString str2 = MyString("rose");
	cout << str1 << endl;
	cout << str2 << endl;
	MyString str3 = str1 + str2;
	//cout << str3 << endl;
}

 

MyString 析构函数

MyString::~MyString()
{
	if (this->pStr != NULL)
	{
		cout << this->pStr <<"析构调用!!" << endl;
		delete[] this->pStr;
		this->pStr = NULL;
	}

	
}

“+” 运算符重载函数

MyString MyString::operator+(MyString & myString)
{
	int newSize = this->Size + myString.Size;

	char* temp=new char[newSize+1];
	//memset(temp, 0, newSize);
	strcat(temp, this->pStr);
	strcat(temp, myString.pStr);

	MyString ansMyString = MyString(temp);
	ansMyString.Size = newSize;

	delete[] temp;
	temp = NULL;

	return ansMyString;
}

有运行结果看str3析构时打印了不知str1和str2的字符,拼接的字符是最后再打印的属于地址越界了,但是str3对象中的Size=8,看来不是在分配空间时出现了问题。

查看operator+函数似乎没有什么问题,使用了strcat()函数进行拼接。但是似乎拼接了一些无关的东西。这里需要分析strcat()的源码。

源码出处 strcat源码分析_wxtRelax的博客-CSDN博客

#include 
#include 

char *strcat(char *dest, const char *src)
{
    //断言dest和src不为空,这一句就可以看出代码的严谨性
    assert(dest != NULL && src != NULL);

    //保留源地址用于返回,用于支持链式操作,
    //如strcat(str1, strcat(str2, str3));
    //在strcpy等中也有同样的操作,很好的思想。
    char *p = dest;

    //移动到dest末尾,不能while(*dest++),这样会移动到''的下一位,想想为什么?
    while(*dest)//等价于(while(*dest) != '')
    {
        dest++;
    }

    //把src拼接到dest后面
    while(*dest++ = *src++);

    return p;
}

发现strcat(dest,src)的源码中拼接是从dest数组中的''开始拼接src的内容的。

恍然大悟!!!

在operator+函数时分配的字符数组temp没有进行初始化,temp是脏内存。需要将其都写成''

char* temp=new char[newSize+1];
memset(temp, 0, newSize);

要加上memset 对temp进行初始化,保证它是“空串”。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/853643.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号