2016-10-30 75 views
0
#include <stdio_ext.h> 
#include <stdlib.h> 
int main() 
{ 
    char a[10],c[10]; 
    int i,b; 

    b=1; 
    i=0; 

    printf(": "); 
    scanf("%s",a); 
    fflush(stdin); 
    __fpurge(stdout); 

    while(i<=10) 
    { 

    c[i]=a[i]+b; 
    i++; 

    } 
    printf("%s",c); 
    return (EXIT_SUCCESS); 
} 

所以事情是我要打印包含在ASCII表下一个字符一个字符,但每次我运行它,我得到这个错误,虽然它看起来尺寸为10的工作:*** ***栈//尝试打印字符

: asdf 
*** stack smashing detected ***: /home/polo/Escritorio/ejemplo/dist/Debug/GNU-Linux/ejemplo terminated 
bteg� c8�l�#w�@��� 
RUN FINISHED; Aborted; core dumped; real time: 4s; user: 0ms; system: 0ms 
+2

'fflush(stdin);'是UB。 –

+1

WTF是'__fpurge'? – melpomene

回答

3

按说

while(i<=10) 

off-by one。它应该是

while(i < 10) 

由于C数组使用基于0的索引。

这就是说,按照C11,章7.21.5.2

如果stream点到输出流或其中最近 操作未输入的更新流,所述fflush函数导致任何未写入数据将该流 传递到主机环境以写入文件; 否则,行为是未定义的 。

所以,不要做fflush(stdin),在技术上,它调用undefined behavior

最后,scanf("%s",a);为缓冲区溢出打开潜在。限制输入缓冲区的长度,如

scanf("%9s",a); //when a is an array of size 10