好吧,我正在尝试制作一个消息加密和解密程序。那么,为什么我会出现分段错误?如果有人可以请帮助我,我将非常感激!我只运行了加密功能。它产生了适当的结果。有什么线索吗?
#include <iostream>
using namespace std;
#define max 1000
#include <string.h>
#include <cstdlib>
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
char * encrypt(char *s)
{
int x = (rand()/((RAND_MAX+1u)/5));
char *res;
int ascii;
switch(x)
{
case 0:
for(int i=0;i<strlen(s);i++)
{
ascii = (int)s[i];
ascii = ascii-19;
res[i+2] = (char)ascii;
}
res[0]='a';
res[1]='$';
break;
case 1:
for(int i=0;i<strlen(s);i++)
{
ascii = (int)s[i];
ascii = ascii+sqrt(strlen(s));
res[i+2] = (char)ascii;
}
res[0]='x';
res[1]='&';
break;
case 2:
case 3:
for(int i=0;i<strlen(s);i++)
{
ascii = (int)s[i];
ascii = ascii-sqrt(strlen(s));
res[i+2] = (char)ascii;
}
res[0]='z';
res[1]='^';
break;
case 4:
for(int i=0;i<strlen(s);i++)
{
ascii = (int)s[i];
ascii = ascii+13;
res[i+2] = (char)ascii;
}
res[0]='a';
res[1]='j';
break;
}
return res;
}
char * decrypt(char *s)
{
int ascii;
char *res;
if(s[0]=='a' &&s[1]=='$')
{
for(int i=0;i<strlen(s);i++)
{
ascii = (int)s[i+2];
ascii += 19;
res[i] = ascii;
}
}
else if(s[0]=='b' &&s[1]=='&')
{
for(int i=0;i<strlen(s);i++)
{
ascii = (int)s[i+2];
ascii -= (strlen(s)*strlen(s));
res[i] = ascii;
}
}
else if(s[0]=='z' &&s[1]=='^')
{
for(int i=0;i<strlen(s);i++)
{
ascii = (int)s[i+2];
ascii +=(strlen(s)*strlen(s));
res[i] = ascii;
}
}
else if(s[0]=='a' &&s[1]=='j')
{
for(int i=0;i<strlen(s);i++)
{
ascii = (int)s[i+2];
ascii -= 13;
res[i] = ascii;
}
}
return res;
}
int main()
{
int ch;
int i=0;
char *s;
char *res;
while(1) {
cout<<endl<<"1.Encrypt\n2.Decrypt";
cout<<endl<<"Choice: ";
cin>>ch;
switch(ch)
{
case 1:
cout<<"\nEnter a message: ";
cin>>s;
res=encrypt(s);
cout<<"\nEncrypted message is: "<<res<<endl;
break;
case 2:
cout<<"\nEnter an Encrypted message: ";
cin>>s;
res=decrypt(s);
cout<<"\nDecrypted message is: "<<res<<endl;
break;
default: exit(0);
}
}
return 0;
}
gdb 给了我这个信息:
Starting program: /home/prasanna/encdec
1.Encrypt
2.Decrypt
Choice: 1
Enter a message: Test Line
Program received signal SIGSEGV, Segmentation fault.
0xb7f41aab in std::basic_istream<char, std::char_traits<char> >& std::operator>><char, std::char_traits<char> >(std::basic_istream<char, std::char_traits<char> >&, char*) ()
from /usr/lib/i386-linux-gnu/libstdc++.so.6