12个有趣的C语言问答

本文分享了12个C语言中常见的编程问题,包括gets()和strcpy()的安全隐患,main()的正确返回类型,内存泄漏的误解,free()的注意事项,atexit()与_exit()的区别,void*与结构体的应用,*与++操作符的顺序,修改代码段的危险,程序自我命名的限制,局部变量作返回地址的风险,以及printf()函数的参数处理方式。这些问题提醒程序员注意C语言中的潜在陷阱和最佳实践。
摘要由CSDN通过智能技术生成

今天在微信公众号CPP开发者上看到了这篇文,特此与大家分享下。

1、gets()方法。

  1 #include <stdio.h>
  2 #include <string.h>
  3 
  4 int main(void)
  5 {
  6         char buff[10];
  7         memset(buff,0,sizeof(buff));
  8 
  9         gets(buff);
 10 
 11         printf("\n The buffer entered is [%s]\n",buff);
 12 
 13         return 0;
 14 }

man下对gets()的解释为:
gets() reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF, which it replaces with ‘\0’. No check for buffer overrun is performed (see BUGS below).

BUGS的解释及建议:
Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.

总结:
gets()会无上限的读取字符,使用时需确保足够的buff,否则容易溢出破坏程序,通常使用fgets代替。

2、strcpy()方法

  1 #include <stdio.h>
  2 #include <string.h>
  3 
  4 int main(int argc,char *argv[])
  5 {
  6         int flag = 0;
  7         char passwd[10];
  8 
  9         memset(passwd,0,sizeof(passwd));
 10 
 11         strcpy(passwd,argv[1]);
 12 
 13         if(0 == strcmp("LinuxGeek",passwd))
 14         {
 15                 flag = 1;
 16         }
 17 
 18         if(flag)
 19         {
 20                 printf("\n Password cracked\n");
 21         }
 22         else
 23         {
 24                 printf("\n Incorrect passwd\n");
 25         }
 26 
 27         return 0;
 28 }

man下关于strcpy有个bug描述:
If the destination string of a strcpy() is not large enough, then any-thing might happen

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值