-4

I am trying to program an encrptor and decryptor. My problem is a pointer that I assigned value first still has the same value as the second. I tried to use free but the problem is still the same. For example, I typed aslkdjlasc(sample only) and the output would be: helloworld

I try to run the program again, then I type daskjda the output would be like doctorxRLD

RLD is from the past value of this pointer. It's supposed to be 7 characters only, but since helloworld is 10, the first 7 letters are replaced by the encryption but the last 3 characters are still printed.

What do I do?

UPDATE: HERE IS PART OF THE CODE:

void encrypt(char *crypt)
{
char *plaintext,*encryption,slash=0x2F;
int i,j,k,flags,f;
encryption=(char *)malloc(sizeof(int));
plaintext=(char *)malloc(sizeof(int));
printf("Enter plaintext, spaces,commas,and dots should be represented as /:\n");
scanf("%s",&*plaintext);
for(i=0;i<strlen(plaintext);i++)
{
    j=1;flags=0;
    while(j<53 && flags==0)
    {
        if(plaintext[i]==slash)
        {
            encryption[i]=slash;
            flags=1;
        }
        if(plaintext[i]==crypt[j])
        {
            encryption[i]=crypt[j-1];
            flags=1;
        }
        k=j+2;
        j=k;
    }
}
printf("%s",encryption);
    free(encryption);
    free(plaintext);
getch();
}

HERE IS THE MAIN

main()
{
char c;
int timer;
char crypt[53]="***i have hidden my encryption code***";
clrscr();
printf("Press e to encrypt, d to decrypt, ESC to exit.\n");
c=getch();
switch(c)
{
    case(0x1b):
        exit(0);
        break;
    case(0x64):
        decrypt(crypt);
        break;
    case(0x65):
        encrypt(crypt);
        break;
    default:
        printf("INVALID. FORCE EXIT IN 3 SEC0NDS.");
        delay(3000);
        exit(0);
}

getch();
}
4

2 回答 2

1

在您的代码中,您正在为字符串分配整数大小(4 字节)的内存

当你这样做

plaintext=(char *)malloc(sizeof(int));

然后通过这样做

scanf("%s",&*plaintext);

您可能正在扫描大小超过四个字符的字符串(但是您只分配了四个字节)

scanf("%s",&*plaintext);相当于scanf("%s",plaintext);( 在前面的语句中,您正在添加不必要的计算。

于 2013-07-28T10:06:25.057 回答
0

是我。我已经明白了。感谢您的所有评论,尽管有些评论很苛刻。哈哈

  1. 我没有使用 malloc,因为显然 DCoder 指出我不知道如何使用它们。
  2. 谢谢 Sanyam Goel 我也修复了我的 scanf。
  3. 我只使用了 2 个指针而不是 4 个。我所做的是在 main 函数中而不是在每个 decrpyt 和 encrypt 函数中实例化它们。像这样:

    main() { char c,*from, *to; ..........

    void encrypt(char *crypt,char *plaintext,char *encryption)

    void encrypt(char *crypt,char *ciphertext,char *decryption)

所以当我打电话给他们中的任何一个时,我只是说:

    case(0x64):
        decrypt(crypt,from,to);
        break;
    case(0x65):
        encrypt(crypt,from,to);
        break;

并在 main 函数中的 switch 结束时:

    free(from); from=NULL;
    free(to); to=NULL;

所以现在我已经消除了不必要的指针和额外的过程。

谢谢大家。:)

于 2013-07-28T11:24:31.707 回答