簡體   English   中英

c-printf(“%s”)打印另外一個@

[英]c - printf(“%s”) prints an additional @

我知道在CS50編程教程上工作。 在這里,我應該破解一個DES加密的字符串。

首先,我將重點放在創建一個64位大數組上,並在鹽中使用所有可能的字符。

在下一步中,我將其放入兩個for循環中,以打印出這兩個for循環的所有可能組合。 那就是我現在所在的位置。

出於調試原因,我只是使用printf("%s",salt)其打印出來。 鹽被定義為炭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
        }
    }
}

您還沒有發布任何代碼,但是我想您沒有為null終止傳遞給printf()的數組。

編輯好猜:您將2個字符設置為char salt[2]並將其傳遞給printf printf打印那些字符,並繼續從內存中讀取超出salt數組末尾的字符,直到找到結束字符串的'\\0'字節為止。

有多種解決方法:

  • 您可以使數組更長,並在字符后設置'\\0'

     char salt[3]; ... salt[2] = '\\0'; printf("%s", salt); 
  • 您可以使用printf格式的精度值為2來從數組中打印最多2個字節:

     printf("%.2s", salt); 
  • 您可以打印數組中的各個字節:

     putchar(salt[0]); putchar(salt[1]); 

至於為什么總是得到@ ,沒有肯定的答案,因為您遇到未定義的行為,所以任何事情都可能發生...但是請注意@值是64 ,這是您存儲在局部變量l的值。 salt數組可能位於變量l之前的內存中。 在小字節序中,值64存儲在l的第一個字節中。

還要注意,不建議將名稱l用作變量,因為這樣的固定字體很難與數字1區分開。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM