8:bufdemo.c
这个函数是要让我们输入一个字符串,放入长度为4的数组中,然后再将数组里面的数据挨个输出,但如果输入的字符串长度超过4,那么就会发生错误。
代码为:
#include <stdio.h>
#include <stdlib.h>
char *gets(char *dest)
{
int c = getchar();
char *p = dest;
while (c != EOF && c != '\n') {
*p++ = c;
c = getchar();
}
*p = '\0';
return dest;
}
/* Read input line and write it back */
void echo()
{
char buf[4]; /* Way too small! */
gets(buf);
puts(buf);
}
void call_echo()
{
echo();
}
/*void smash()
{
printf("I've been smashed!\n");
exit(0);
}
*/
int main()
{
printf("Type a string:");
call_echo();
return 0;
}
/*gcc -S bufdemo.c的时候会有警告
bufdemo.c: In function ‘echo’:
bufdemo.c:22:5: warning: ‘gets’ is deprecated (declared at /usr/include/stdio.h:638) [-Wdeprecated-declarations]
gets(buf);
^
运行结果:
***@ubuntu:/mnt/hgfs/share/csapp_code$ ./a.out
Type a string:0123
0123
***@ubuntu:/mnt/hgfs/share/csapp_code$ ./a.out
Type a string:012345
012345
*** stack smashing detected ***: ./a.out terminated
已放弃 (核心已转储)