今天寫代碼時使用了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;
}