gpt4 book ai didi

c - 函数只工作一次 - C

转载 作者:太空狗 更新时间:2023-10-29 15:51:12 25 4
gpt4 key购买 nike

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

编辑:如果发布这么多内容过多,请随意修改代码。我已经删除了很多内容,所以我不会只是粘贴我的项目并希望有人修复它。

// 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;
}

最佳答案

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

可能是问题所在,因为它始终是 sizeof(char *)。我想你想要

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

关于c - 函数只工作一次 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9678188/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com