CSAP学习日志----数组和栈

这段代码用于检测数组元素的存储。
先上代码:

/* 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,检测到堆栈粉碎,就会发生报错,即已放弃 (核心已转储)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值