the posted code is:
- including a header file those contents are not used
- trying to 'sprintf()` a 3 char integer into a single byte
- returning pointers to local variables
- is not terminating the strings to be printed with a NUL byte
Note: size_t
is a well known definition for unsigned long int
The following suggested code corrects all of the above problems and a few others.
#include <stdio.h> // printf()
#include <stdlib.h> // exit(), EXIT_FAILURE, malloc(), free()
//#include <math.h>
#include <string.h> // strlen()
char* readLine_str_test_encrypt( char *, size_t );
char* readLine_str_test_decrypt( char *, size_t );
int main ( void )
{ //body
char string[] = "readLine";
char * encryptedString = readLine_str_test_encrypt( string, strlen(string) );
// Note: the encrypted string may not be printable
printf("%s\n", encryptedString );
char * decryptedString = readLine_str_test_decrypt( encryptedString, strlen(string) );
printf( "%s\n", decryptedString );
free( encryptedString );
free( decryptedString );
} // end function: main
char* readLine_str_test_decrypt( char *encryptedString, size_t length)
{
char *string = NULL;
if( NULL == ( string = malloc( length +1) ) )
{// then malloc failed
perror( "malloc for decrypted string failed" );
exit( EXIT_FAILURE );
}
// implied else, malloc successful
for ( size_t i=0; encryptedString[i]; ++i )
{
string[i] = encryptedString[i] ^22;
}
string[length] = '\0';
return string;
} // end function: readLine_str_test_decrypt
char* readLine_str_test_encrypt( char *stringToEncrypt, size_t length )
{
char *output = NULL;
if( NULL == (output = malloc( length+1 ) ) )
{ // then, malloc failed
perror( "malloc for work area failed" );
exit( EXIT_FAILURE );
}
// implied else, malloc successful
for( size_t i=0; stringToEncrypt[i]; ++i)
{
output[i] = stringToEncrypt[i] ^22;
}
output[length] = '\0';
return output;
} // end function: readLine_str_test_encrypt
the output from the above code is:
dswrZxs
readLine