malloc的坑

今天写代码时使用了malloc,觉得这种函数可以张口就来,哪知居然也踩了坑,好吧,我们学习一定要认真,楼主最近找工作才发现自己是多么的垃圾,废话不多说。上代码:

注意那行代码:memset(strjam,0, strlen(strjam));注意我这里初始化长度是strlen(strjam)->这个长度是不是我之前分配的101个字节呢,答案是不是的malloc实际分配的内存大小是多于你申请的内存空间的,所以这里长度不能用strlen(strjam),如果用了那么恭喜你,你把除了保存数据的地方也给初始化了,这导致我释放这块内存的时候直接异常了。所以,童鞋,你在写代码时malloc和memset结合使用时一定要确保两者的长度要对应一致,你再用malloc分配内存时显示分配了多少就应该显示的memset多少,比如我这里改为:memset(strjam,0, 101 * sizeof(char))。就酱

#include<iostream>
#include<string>

using namespace std;

void Encrypt(const char aucPassword[], char aucResult[])
{
	int i = 0;
	for (i = 0; i < strlen(aucPassword); i++)
	{
		if (aucPassword[i] >= 'a'&&aucPassword[i] <= 'z')
		{
			if (aucPassword[i] == 'z') aucResult[i] = 'A';
			else
			{
				aucResult[i] = aucPassword[i] - 'a' + 'B';
			}
		}

		if (aucPassword[i] >= 'A'&&aucPassword[i] <= 'Z')
		{
			if (aucPassword[i] == 'Z') aucResult[i] = 'a';
			else
			{
				aucResult[i] = aucPassword[i] - 'A' + 'b';
			}
		}

		if (aucPassword[i] >= '0'&&aucPassword[i] <= '9')
		{
			if (aucPassword[i] == '9') aucResult[i] = '0';
			else
			{
				aucResult[i] = aucPassword[i]+1;
			}
		}
	}

	aucResult[i] = '\0';
}

int unEncrypt(char result[], const char password[])
{
	int i = 0;
	for (i = 0; i < strlen(password); i++)
	{
		if (password[i] >= 'a'&&password[i] <= 'z')
		{
			if (password[i] == 'a') result[i] = 'Z';
			else
			{
				result[i] = password[i] - 'b' + 'A';
			}

			if (password[i] >= 'A'&&password[i] <= 'Z')
			{
				if (password[i] == 'A') result[i] = 'z';
				else
				{
					result[i] = password[i] - 'B' + 'a';
				}
			}

			if (password[i] >= '0'&&password[i] <= '9')
			{
				if (password[i] == '0') result[i] = '9';
				else
				{
					result[i] = password[i] - 1;
				}
			}
		}
	}
	result[i] = '\0';
	return 0;
}

int main()
{
	string str1;
	string str2;

	cin >>str1;
		cin >> str2;

		int i = 0;
		//char strjam[101] = "";

		char *strjam = NULL;
		
		strjam=(char *)malloc(101*sizeof(char));
		cout << strlen(strjam) << endl;
		memset(strjam,0, strlen(strjam));

		Encrypt(str1.data(), strjam);

		//unEncrypt((char*)str2.data, strjem);

		cout << strjam << endl;
		//cout << strjem << endl;

		free(strjam);


	system("pause");
	return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值