【问题标题】:My C program's "for" loop is stalling after 3 iterations我的 C 程序的“for”循环在 3 次迭代后停止
【发布时间】:2020-06-03 08:38:17
【问题描述】:

我已经制作了一个简单的 C 程序来进行逆向练习 - 但是,当我输入名称和密码时,它会在 for 循环中迭代三次,然后停止并有一个旋转的光标,最后没有输出返回到命令行界面。我已经对我的算法进行了更改并确保它是正确的(这里的函数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 name\n");
    printf("Enter password: ");
    scanf("%s", p);
    printf("Entered password\n");

    int j;
    for (j = 0; j < strlen(N); j++) {
        printf("Iterating, iteration %d\n", 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:\MinGW\bin>gcc "\\Mac\Home\Desktop\My Crackme.c" -o "\\Mac\Home\Desktop\MyCrackme.exe"
C:\MinGW\bin>"\\Mac\Home\Desktop\MyCrackme.exe"

Enter name: Jack
Entered name
Enter password: Not Jack
Entered password
Iterating, iteration 0
Iterating, iteration 1
Iterating, iteration 2

C:\MinGW\bin>

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

【问题讨论】:

  • 你打开编译器警告了吗?
  • N[j] == 0 永远不会是真的,因为j&lt;strlen(N)
  • @PaulOgilvie x 是第一个函数,n 在三个字符串下面声明。我包括检查N[j] == 0,因为据我所知,N 将包含输入的字符,然后用0 填充以填充到长度16 - 还是只是建议的长度?
  • strlen 在第一个空字符处停止计数。
  • 我认为问题出在strcat(r, &amp;n);,因为*n 不是以空字符结尾的字符串,而是单个字符。 strcat 复制到它遇到的第一个 null ,这里不会。所以你的r 会溢出,导致中止。

标签: c for-loop mingw


【解决方案1】:

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

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

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

或(更好):

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

【讨论】:

  • 看起来可行 - 谢谢保罗! (C 有点与字符/字符串 ngl 混淆:P)
  • strcat(r, "A") 也会起作用,而不是奇怪的“x”函数。
  • @Lundin x 包含一个算法,"A" 是一个占位符(正如我在问题中解释的那样,替换它没有帮助)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-23
  • 2020-07-13
  • 2021-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-05
相关资源
最近更新 更多