我的 C 程序的 "for" 循环在 3 次迭代后停滞不前



我做了一个简单的 C 程序来反转练习 - 但是,当我输入名称和密码时,它会在for循环中迭代三次,然后停止并有一个旋转光标,最后退出,没有输出回 CLI。我已经对我的算法进行了更改并确保它是正确的(这里x的函数不是问题,因为即使返回其静态值也会发生冻结(。在我的程序中,我误入歧途的哪个地方?(这是我学习 C 语言的第一天,IDEONE 说我有一个缓冲区溢出。

程序:

#include <stdio.h>
#include <string.h>
int x(char* s, int c) {
return 65;
}
int main(void) {
char N[16] = ""; // Entered name
char p[16] = ""; // Entered password
char r[16] = ""; // Result of applying keygen `x` to `N` (`p` should be this to be correct)
char n;
printf("Enter name: ");
scanf("%s", N);
printf("Entered namen");
printf("Enter password: ");
scanf("%s", p);
printf("Entered passwordn");
int j;
for (j = 0; j < strlen(N); j++) {
printf("Iterating, iteration %dn", j);
if (N[j] == 0) {
break;
}
n = x(N, j);
strcat(r, &n);
}
if (strcmp(r, p) == 0) {
printf("Correct!n");
}
else {
printf("Incorrect!n");
}
return 0;
}

命令行界面:

C:MinGWbin>gcc "\MacHomeDesktopMy Crackme.c" -o "\MacHomeDesktopMyCrackme.exe"
C:MinGWbin>"\MacHomeDesktopMyCrackme.exe"
Enter name: Jack
Entered name
Enter password: Not Jack
Entered password
Iterating, iteration 0
Iterating, iteration 1
Iterating, iteration 2
C:MinGWbin>

这似乎只发生在我使用 MinGW 编译成exe- 在我的 Mac 上使用gcc编译成通用可执行文件会产生一个看似有效的程序。但是,我需要一个exe文件。所有的帮助感谢!

问题出在strcat(r, &n);*n因为 不是以 null 结尾的字符串,而是单个字符。strcat复制直到它遇到的第一个 null,但在这里不会。因此,您的r会溢出,从而导致中止。

您必须手动附加字符而不是strcat,例如:

int len= strlen(r);
*(r+len  )= n;
*(r+len+1)= '';

或(更好(:

int len= strlen(r);
if (len<sizeof(r)-1) {
*(r+len  )= n;
*(r+len+1)= '';
}

最新更新