Reputation: 6939
My biggest problem is on this line:
for(i=0;i<=strlen(enc);i++) ->
7th line of the function decifrar: It keeps the loop even with the memset used to clear the memory (it's even bigger than the string length)
Note if I use the actual length of the string in that line the code does works (i.e. replacing strlen(enc) with 60 )
void decipher(int k, char *enc){
char alfa[]="9876543210zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA9876543210zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA";
char *pch;
int i;
for(i=0;i<=strlen(enc);i++){
pch=strchr(alfa, enc[i]);
if (pch) enc[i] = *(pch + k),enc[i]=tolower(enc[i]);
}
printf("%s",enc);
}
int main(){
int keys[6]={1,4,15,24,12,20},i;
char *txt="rfgr r hz grkgb fvzcyrf dhr cergraqr fre grfgnqb ab cebtenzn";
char *txttemp=malloc(sizeof(char)*1024);
for(i=0;i<6;i++){
printf("\n\n\t Attempt number: %d\n\n",i+1);
memset(txttemp,'\0',sizeof(char)*strlen(txt)+30);
memcpy(txttemp, txt, strlen(txt));
decipher(keys[i],txttemp);
}
return 0;
}
What is the point that I am missing? Is the usage of strlen wrong?
Upvotes: 2
Views: 465
Reputation: 3799
It's <
not <=
in the for-loop.
But as a Note: avoid that pattern. Strlen means you count the length of the string, but you probably should already know it from somewhere (i.e. when you receive it: the file length, the number of charecters returned etc...). Save it and take that value as the length. This is the source of a lot of security holes in programs (a buffer overflow).
std::string
has this as a built-in functionality and it's what I would recommend over a plain char* almost all of the time (that is if you can use C++)
Upvotes: 7