Error: Abort trap 6 - String obfuscation

Error: Abort trap 6 - String obfuscation

我正在尝试为字符串混淆编写代码,但在 运行 时它给了我中止陷阱:6 错误。非常感谢任何想法:

#include <stdio.h>
#include <math.h>
#include <string.h>

char* readLine_str_test_encrypt();
char* readLine_str_test_decrypt();

int main () { //body 

printf("%s\n", readLine_str_test_encrypt());

printf("%s\n", readLine_str_test_decrypt());


}

char* readLine_str_test_decrypt() {
static unsigned char string[9] = {100, 115, 119, 114, 90, 127, 120, 115, 22};

static int i = 0;

for (; i < 9; ++i) {
    string[i] ^= 22;
}

return (char*)string;
}

char* readLine_str_test_encrypt()
{
static unsigned char string[9] = "readLine";
char output[9];
char* output_start=output;
static int i =0;
for(; i < 9; ++i)
{
    //string[i] = string[i]^22;
    output_start += sprintf(output_start,"%d",string[i]^22);

}

return output_start;
}

我的解密函数 运行 成功。

readLine_str_test_encrypt 中,您正在 return 指向变量 output 的指针。该变量是局部变量,在函数退出时超出范围。

改为

static char output[9];  

错误消失了。

详细了解为什么不 return 局部变量 here

发布的代码是:

  1. 包括一个头文件那些内容没有用到
  2. 尝试将 3 个字符的整数“sprintf()”转换为单个字节
  3. 返回指向局部变量的指针
  4. 未使用 NUL 字节终止要打印的字符串

注意:size_tunsigned long int

的众所周知的定义

以下建议的代码纠正了上述所有问题和其他一些问题。

#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] = '[=10=]';

    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] = '[=10=]';

    return output;
} // end function: readLine_str_test_encrypt

以上代码的输出是:

dswrZxs
readLine