c++函数返回中间包含‘\0‘动态字符串且无需外部释放内存的解决方案

c++函数返回中间包含’\0’动态字符串且无需外部释放内存的解决方案

c++函数返回中间包含’\0’动态符串,一般采用返回char *的方式,同时返回字串长度,但由于在函数内是动态分配的内存,需要在外部释放,否则会造成内存泄漏,在网上找了许久,也没有找到好的解决方案,后来在研究string类构造的基础上,找到了无需外部手动释放内存的解决方案。

不多写了,上源码。

#include <iostream>
#include <string>
#include <vld.h>
using namespace std;

// len为引用返回字符串长度,此处只是为了验证,实际不需要
string returnChars(int &len)
{

	// 字符串赋值,此处只是示例
	char pszStr[] = "aêcd\0efgh\0ijkl";

	// sizeof计算出的字符数组长度包括结束符
	len = sizeof(pszStr) - 1;

	// 定义动态字符串
	char * pszChars = (char *)calloc(1, len);

	// 内存拷贝
	memcpy(pszChars, pszStr, len);

	// 如果字符串长度为0
	if (len == 0)
		return "";

	// 构造string
	string str(pszChars, len);

	// 释放动态字符串内存
	free(pszChars);
	pszChars = nullptr;

	// 返回string
	return str;
}

int main()
{
	int len;
	string str = returnChars(len);
	int strLen = str.length();
	int sizeStr = str.size();

	// 只会输出第一个'\0'之前的字符串
	cout << endl << str << endl << endl;

	cout << "return len = " << len << endl;
	cout << "string str len = " << strLen << endl;
	cout << "string str size = " << sizeStr << endl << endl;
	cout << "序号	" << "字符	" << "ASCII值" << endl;
	for (int i = 0; i < len; i++)
		cout << i << "	" << str[i] << "	" << int(str[i]) << endl;
	return 0;
}

运行结果

Visual Leak Detector read settings from: C:\Program Files (x86)\Visual Leak Detector\vld.ini
Visual Leak Detector Version 2.5.1 installed.

aêcdefghijkl

return len = 15
string str len = 15
string str size = 15

序号    字符    ASCII值
0       a       97
1               -88
2               -70
3       c       99
4       d       100
5               0
6       e       101
7       f       102
8       g       103
9       h       104
10              0
11      i       105
12      j       106
13      k       107
14      l       108
No memory leaks detected.
Visual Leak Detector is now exiting.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值