c - printf("%s")打印额外的@

The*_*282 -1 c printf cs50

我正确地知道cs50编程教程.在这里,我应该破解DES加密的字符串.

首先,我专注于创建一个64位大阵列,其中包含盐中使用的所有可能的字符.

在下一步中,我将其抛入两个for循环中,以打印出这两个for循环的所有可能组合.这就是我现在所处的位置.

出于调试原因,我只是打印出来printf("%s",salt).盐被定义为char salt[2].但由于某种原因,它总是打印出来xx@(xx每次按预期更改,我不知道@它来自哪里).

首先,我认为它可能会出于一些奇怪的原因而超出阵列并@从随机存储器中获取.这就是我将它从我的在线IDE复制到我的本地XCode的原因.仍然是相同的@符号.而现在我对它的来源感到困惑@.

链接到我的代码.

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define _XOPEN_SOURCE       // DES - implementation
#include <unistd.h>

// shorthands
#define cypher argv[1]

#define ascii_dot 46
#define ascii_slash 47
#define ascii_zero 48
#define ascii_nine 57
#define salt_size 64

#define majA 65
#define majZ 90

#define minA 97
#define minZ 122

int main(int argc, string argv[]) {
    // Checking input
    if (argc != 2) {
        printf("<usage>\n<./crack <password_hash>");
        return 1;
    }

    // Create a salter
    // 2 * 26 for letters + 10 for numbers + dot and slash = 64 = salt_size
    char salt_crystal[salt_size];

    {   // Own scope to not waste space for salt_iterator
        int salt_iterator = 0; // used to create salt crystals

        //minuscels
        for (int i = minA; i <= minZ; i++)
            salt_crystal[salt_iterator++] = (char)i;
        //majuscels
        for (int i = majA; i <= majZ; i++)
            salt_crystal[salt_iterator++] = (char)i;
        //ascii_dot to 9
        for (int i = ascii_dot; i <= ascii_nine; i++)
            salt_crystal[salt_iterator++] = (char) i;
    }

    // make the salt and forward it to the next function 
    for (int i = 0, l = salt_size; i < l; i++) {
        char salt[2];
        salt[0] = salt_crystal[i];
        for (int i2 = 0, l2 = salt_size; i2 < l2; i2++) {
            salt[1] = salt_crystal[i2];
            printf("%s ", salt); // DEBUG
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

chq*_*lie 5

你没有发布任何代码,但我猜你没有null终止你传递给的数组printf()...

编辑好猜测:你设置2个字符char salt[2]并将其传递给printf.printf打印那些并继续从salt数组末尾的内存中读取字符,直到找到一个'\0'结束字符串的字节.

有不同的方法来解决这个问题:

至于为什么你一直得到一个@,没有明确的答案,因为你遇到了未定义的行为,所以任何事情都可能发生......但是请注意,它@具有值64,即存储在局部变量中的值l.salt数组可能位于l变量前的内存中.在小端,值64存储在第一个字节中l.

另请注意,l建议不要为变量使用该名称,因为很难区分1固定字体中的数字.