c problems series 1

来自http://tunps.com/c-problems-series-1

1.
>老师你好,有个C语言问题请教。
> #include <stdio.h>
> main()
> {
>       union
>       {
>            char ch[2];
>            int d;
>       }s;
>       s.d=0x4321;
>       printf("%x,%x\n",s.ch[0],s.ch[1]);
>       
> }
> 为什么输出21,43 而不是43,21
> 
> 
这个问题不复杂,考到了数据在内存中如何存储问题。数据在内存中存储是从低位到高位,也
就是说先存储的21,在存储的43.所以按序输出时候就输出这个结果了。

2.
%ns和%.ns
从 Planet Chinese Security Community 作者:void@planetchinesesecuritycommunity.org(void)
这段代码有什么问题?
void func(char *p) {
   char buf[10+1];
   memset(buf,0,sizeof(buf));

   // limit string to 10 chars
   sprintf(buf,"%10s",p);
   printf("Hello, %s\n",buf);
}

答案:
%10s只是用于宽度对齐,超过10字节,仍然全部拷贝,导致溢出.
%.10s才是限制了拷贝长度为10字节

About tunpishuang

just 4 fun·····
This entry was posted in 未分类 and tagged . Bookmark the permalink.

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>