这段代码用于检测数组元素的存储。
先上代码:
/* Demonstration of buffer overflow */
#include <stdio.h>
#include <stdlib.h>
/* Implementation of library function gets() */
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;
}
运行结果如下:
gec@ubuntu:/mnt/hgfs/gx$ gcc 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);
^
gec@ubuntu:/mnt/hgfs/gx$ ./bufdemo
Type a string:0123
0123
gec@ubuntu:/mnt/hgfs/gx$ ./bufdemo
Type a string:01234
01234
*** stack smashing detected ***: ./bufdemo terminated
已放弃 (核心已转储)
在用gcc编译时,出现了警告。
在程序的运行结果中出现了报错:
定义的char 型数组长度为4个字节,若用户输入的数据不超过4个,那这些数据是保存在数组中的,输出的时候从数组中依此输出。若用户输入的数据超过了4个,则超出数组大小的数据被保存在栈里,这些存在栈里的元素输出即出栈。
因此若长度超过4,检测到堆栈粉碎,就会发生报错,即已放弃 (核心已转储)。