【问题标题】:Printf char[] buffer overflowPrintf char[] 缓冲区溢出
【发布时间】:2012-11-13 17:29:42
【问题描述】:

我有这个问题,我的名字是一个字符[20],如果我插入一些字符,数组就会溢出并写入另一个数组(认知)。

我尝试使用 puts() 更改 scanf(),但最后一个无法正常工作,因为它跳出输入并且什么也不读取。


有人知道解决方案吗?

这里是代码

void addStudent(){
    struct student s;
    printf("Inserire Nome: ");
    scanf("%20s",s.nome);
    printf("\nInserire Cognome: ");
    scanf("%30s",s.cognome);
    printf("\nInserire eta': ");
    scanf("%d",&s.anni);
}

结果

Inserire Nome: cjhsdjkhbsdkhfgsdjkhfgskjhgjkhsfs

Inserire Cognome: 
Inserire eta': 

【问题讨论】:

    标签: c printf


    【解决方案1】:

    更改为"%19s"。它必须比数组大小小一,因为scanf() 写入了一个空终止符。在调用scanf() 之后,您需要跳过任何未处理的输入,这可以通过阅读直到下一个换行符来实现:

    int ch;
    while ((ch = getchar()) != EOF && ch != '\n');
    

    【讨论】:

    • printf("Inserire Nome:"); scanf("%19s",s.nome); printf("\nInserire Cognome:"); scanf("%29s",s.cognome); 同样的问题:' Inserire Nome: gauysdgjhasdgjhkasgdjhagdjhgad Inserire Cognome: Inserire eta': '
    • 你能举个例子吗? @hmjd struct student s; printf("Inserire Nome: "); scanf("%19s",s.nome);
    • @PsyKoWebMari,在scanf()之后你需要跳过剩余的字符就行了。您可以使用我在此答案中发布的示例循环。不跳过则由下一个scanf()处理。
    • 好的,谢谢,我现在明白了。干得好!
    【解决方案2】:

    你少了一个字符,你应该为空字节留一个字符,同样适用于s.cognome

    scanf("%19s",s.nome);
    

    另外,scanfputs 不能互换,第一个读取一些内容,第二个输出一些内容,你可能是指 gets 或更好的 fgets

    fgets(s.nome, 20, stdin);
    

    【讨论】:

    • 我不知道为什么,但是如果我使用 fgets,程序会跳转输入并转到下一条指令。 @mux
    • @PsyKoWebMari fegts 不是 puts 试试看它是否有效。
    • 它跳... printf("Inserire Nome: "); fgets(s.nome, 19, stdin); Inserire Nome: Inserire Cognome:
    猜你喜欢
    • 2018-12-31
    • 2015-12-16
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 2011-02-17
    • 2013-11-06
    • 2013-04-11
    • 2015-07-07
    相关资源
    最近更新 更多