2012-03-13 72 views
3

我一直在尝试制作一个基本的XOR头文件以供将来的某些程序使用。到目前为止,我几乎可以完成所有工作,但似乎无法两次使用相同的功能。如果我调用该函数来加密它的字符串,但是如果我再次调用它,它会崩溃。我不知道我是在记忆方面做错了什么,或者是错过了一些明显的东西。希望有人能指出这个缺陷,因为我似乎无法找到任何错误。函数只能工作一次 - C

编辑:如果张贴这么多太多,请随意修剪代码。我已经拿出了很多,所以我不只是粘贴我的项目,希望有人修复它。

// Main.c 
#define MAX_LENGTH 255 
#define KEY_SIZE 8 
int main(int argc, char *argv[]) { 
    //Get String to XOR 
    char *input = malloc (MAX_LENGTH); 
    printf("Enter a string to encrypt: "); 
    fgets(input, MAX_LENGTH, stdin); 

    if(input[strlen (input) - 1] == '\n') { 
     input[strlen (input) - 1] = '\0'; 
    } 

    //Create a random key 
    char *pass = _create_key(KEY_SIZE); 
    int len = strlen (input); 
    printf("Length of key is %d\n", KEY_SIZE); 
    printf("Entered String: %s - Password: %s\n", input, pass); 

    //Encrypt works fine 
    char *encrypted = malloc (sizeof (input)); 
    _xor_str_s(input, pass, len, encrypted); 
    printf("Encrypted String: %s\n", encrypted); 

    char *decrypted = malloc (sizeof (input)); 
    //Crashes here 
    _xor_str_s(encrypted, pass, len, decrypted); 
    printf("Decrypted String: %s\n", decrypted); 
    return 0; 
} 

//Header File Function 
void _xor_str_s(char *str, char *pass, int len, char *out) { 
    int i = 0; 
    for(i = 0; i < len; i++) { 
     *(out + i) = str[i]^pass[i % strlen (pass)]; 
    } 
    *(out + i) = 0; 
} 

char * _create_key(int len) { 
    len = !len ? 16 : len; 
    char *ret = (char *)malloc (len); 
    unsigned int _GLOBAL_SEED_ = (unsigned int)time(NULL); 
    srand (_GLOBAL_SEED_); 
    int i = 0; 
    for(i = 0; i < len; i++) { 
     ret[i] = (char)(rand() + 1); //+1 avoids NULL 
    } 
    ret[i] = '\0'; 
    return ret; 
} 
+0

你收到的错误信息是什么? – 2012-03-13 04:04:41

+0

没有编译错误,它只是在运行时崩溃而没有消息。我应该补充的另一件事是,它可以处理4个字母和其他长度的字符,但总是可以在任何可以被8和其他随机长度整除的东西上崩溃。另一件事让我想知道发生了什么。 – ozdrgnaDiies 2012-03-13 04:06:44

+0

您在'_xor_str_s'中缺少'NULL'引用检查。在'malloc'调用之后总是检查'NULL'。 – 2012-03-13 04:07:40

回答

11
char *encrypted = malloc (sizeof (input)); 

可能是问题,因为这将永远是sizeof(char *)。我想你想要

char *encrypted = malloc (strlen (input) + 1); 
+0

这是一个很好的例子,说明当你确定它是正确的时候掩饰错误是多么容易。这立即解决了问题。总是很好,有一个新的眼睛来发现这些类型的东西。感谢你的回答! – ozdrgnaDiies 2012-03-13 04:16:55