【问题标题】:Printing a char in C with printf wont print [closed]用 printf 在 C 中打印一个字符不会打印 [关闭]
【发布时间】:2016-10-28 18:39:44
【问题描述】:

我有以下代码:

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

int main(void)
{
    char buff[50];
    int pass = 0;

    printf("\n Enter the password : \n");
    gets(buff);
    char str[80];
    strcat(str, "nw");
    strcat(str, "ww");
    strcat(str, "io");
    strcat(str, "oi");

    char str2[22];
    strcat(str2, "jm");
    strcat(str2, "qw");
    strcat(str2, "ef");
    strcat(str2, "io");
    strcat(str2, "nw");
    strcat(str2, "ce");
    strcat(str2, "or");
    strcat(str2, "ww");
    strcat(str2, "qf");
    strcat(str2, "ej");
    strcat(str2, "oi");


    if(strcmp(buff, str))
    {
        /*  we sf  as  df er fd xc yyu er we nm hj ui ty as asd qwe er t yu as sd df rt ty qw sd password    */

        printf ("\n Wrong Password \n");
    }

    else
    {
        printf ("\n Correct Password \n");
        pass = 1;
    }

    if(pass)
    {
        printf ("\n\n\n\n\n\n\n%s", str2);
    }

    return 0;
}

当我运行它时,我得到:

root@images:~# ./root.flag

 Enter the password :
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

 Wrong Password







Segmentation fault (core dumped)

它打印换行符,但不打印 str2 中存储的值。如何让 str2 打印到屏幕上?我对 C 相当陌生,所以我不知道为什么这不起作用。我可能忽略了一些简单的事情。

【问题讨论】:

  • 我在您的代码中没有看到 %c 转换类型说明符。

标签: c char printf


【解决方案1】:

buff 只有 50 个字符,但您输入了 131 个“A”,因此您的行为未定义。 str2 也只有 22 个字符,它需要是 23 并且应该是 '\0' NULL 终止以打印它。 事实上,你不应该在它被初始化之前对它进行搜索。试试str2[23] ={0};

函数 strcat(str, new) 查找字符串 str 的末尾以开始在 new 中添加字符。字符串的结尾定义为 '\0' 或零。您需要初始化局部变量以确保它们具有您想要的值。代码是str1[80]={0};str2[23]={0};

【讨论】:

  • strcats 也是 UB,因为 strstr2 没有初始化
  • @yano 知道了,刚刚更新了答案。
  • 呃,大声笑谁能告诉我这一切在代码中意味着什么?
  • 哦,好的,有帮助
  • 所以 "char str[9] = {0};"或者只是“str[9] = {0};”在我做 strcat 之前?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多