Mahesh wrote:
#include <stdio.h>
#include <string.h>
#include <malloc.h>
Not a standard C header; use <stdlib.hfor malloc(), realloc(),
free().
int main(void)
{
int key = 120;
char *s = "String to Encrypt using XOR";
char *ss = s;
char echar;
char dchar;
size_t sizeofmsg = strlen(s)*sizeo f(char*);
Wrong calculation.
It should be (number of elements)*(size of the type s points to).
That is,
sizeofmsg = (strlen(s) + 1) * sizeof *s;
as s points to char and sizeof (char) is guaranteed to be 1,
you can write
sizeofmsg = strlen(s) + 1;
The "+1" stems from the string terminator that is not included
in the string length but contributes to the string's size.
>
char *emsg = (char*)malloc(s izeofmsg);
char *dmsg = (char*)malloc(s izeofmsg);
Note that the cast is unnecessary and can hide an error; around
here,
T *p = malloc(NumberOf Elems * sizeof *p);
is recommended.
char *ddmsg = dmsg;
char *eemsg = emsg;
int lenofmsg = strlen(s);
int count=0;
int i=0;
while(count++<s trlen(s)){
echar = (char)(*ss^key) ;
Note that XOR encryption of the value key leads to 0 ('\0'),
which also is the string terminator.
emsg = &echar;
You probably mean
*emsg = echar;
&echar is just that, the address of echar; you do not change
the contents of the storage area you got from malloc().
So, in every iteration, you point emsg at the same object.
Note that for s, you iterate on the copy, and for emsg, you
iterate on the "original". This can lead to problems.
emsg++;
ss++;
}
count=0;
emsg = eemsg; // HERE when i restore the address of emsg via
eemsg, i'm not able to
// decrypt. How to restore the address of
original pointer to char ?.
// style comments break easily on usenet; I recommend that you use
/**/ comments which cannot change semantics or "compilabil ity" due
to line breaks
i=0;
printf("\n");
while(count++<s trlen(s)){
echar = *emsg;
dchar = (char)(echar ^ key);
ddmsg = &dchar;
printf(" %c",dchar);
emsg++;
ddmsg++;
}
printf("\n");
getch();
return 0;
}
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.