gpt4 book ai didi

c - 字符串末尾的随机字符

转载 作者:太空宇宙 更新时间:2023-11-04 05:35:22 25 4
gpt4 key购买 nike

我在 C 语言(使用 GCC)中创建了一个加密字符串的函数,但我在解密字符串的末尾得到了随机字符。该函数将在第一个字符处保存输入字符串的长度,在第二个字符处保存使用的键(第一个字符 -1)。所有要加密的字符串的长度都在 10 到 30 之间,所以我希望在转换为存储为 char 时没有问题。

完整代码在这里:

#include <stdio.h> //printf
#include <stdlib.h> //malloc
#include <string.h> //strlen

char* x(const char* toEncrypt);
char* y(const char* toDecrypt);

int main() {
const char *secret = "hellohello";
printf("original: %s\n", secret);

const char* crypted = x(secret);
printf("crypted: %s\n", crypted);

const char* decrypted = y(crypted);
printf("decrypted: %s\n", decrypted);

return 0;
}

char* x(const char* toEncrypt) {
printf("x->toEncrypt = %s\n", toEncrypt);

int offset = 0, i = 0;
int length = strlen(toEncrypt);
printf("\tx->length = %d\n", length);

char key = ((char)(*toEncrypt))-1;
printf("\tx->key = %c\n", key);

char* output = (char*)malloc(length+3); //toEncrypt length + (length + key + null)

output[offset++] = (char)length;
output[offset++] = key;

for (i = 0; i < length; i++) {
printf("i = %d\toffset = %d\tchar = %c\n", i, offset, toEncrypt[i]);
output[offset++] = toEncrypt[i] ^ key;
}
output[offset] = '\0';

printf("\tx->output = %s\n", output);
return output;
}

char* y(const char* toDecrypt) {
printf("y->toDecrypt = %s\n", toDecrypt);

int offset = 0, i = 0;
int length = (int)toDecrypt[offset++] ;
printf("\tx->length = %d\n", length);

char key = (char)toDecrypt[offset++];
printf("\ty->key = %c\n", key);

char* output = (char*)malloc(length+1);

for (i = 0; i < length; i++) {
printf("i = %d\toffset = %d\tchar = %c\n", i, offset, (char)toDecrypt[offset] ^key);
output[i] = toDecrypt[offset++] ^ key;
}

output[offset] = '\0';

printf("\ty->output = %s\n", output);
return output;
}

输出:

original: hellohello
x->toEncrypt = hellohello
x->length = 10
x->key = g
i = 0 offset = 2 char = h
i = 1 offset = 3 char = e
i = 2 offset = 4 char = l
i = 3 offset = 5 char = l
i = 4 offset = 6 char = o
i = 5 offset = 7 char = h
i = 6 offset = 8 char = e
i = 7 offset = 9 char = l
i = 8 offset = 10 char = l
i = 9 offset = 11 char = o
x->output =
g
crypted:
g
y->toDecrypt =
g
x->length = 10
y->key = g
i = 0 offset = 2 char = h
i = 1 offset = 3 char = e
i = 2 offset = 4 char = l
i = 3 offset = 5 char = l
i = 4 offset = 6 char = o
i = 5 offset = 7 char = h
i = 6 offset = 8 char = e
i = 7 offset = 9 char = l
i = 8 offset = 10 char = l
i = 9 offset = 11 char = o
y->output = hellohellobe
decrypted: hellohellobe

最佳答案

我认为问题在于这个语句(在函数 y() 中 — 在函数 x() 中的相同语句是可以的):

output[offset] = '\0';

应该是:

output[i] = '\0';

更改此设置应该有效。

关于c - 字符串末尾的随机字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40097524/

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