size_t的祕密

今天在看一個經典的雙鏈表的時候看到了一個類型size_t,這個類型在此之前也經常見到,但是並沒有太在意,一直都把他當成整形在用,但是在分析雙鏈表的代碼時發現了一個問題,跟我理解的有些出入,但是運行代碼他的寫法卻是對的,於是就開始找我理解出錯的地方,從頭看了一遍,發現唯一的問題就是size_t類型,上網搜索了一下,講解的並不多,一般都說把他當int用,於是自己寫了一個代碼測試下,代碼如下:

#include <stdio.h>
int main()
{
size_t a=-1;
size_t b=90;
if (a<b)
printf("a bao chi bu bian/n");
else
printf("a bei bian yi wei bu ma/n");
}

運行結果爲:

[root@localhost dry]# ./cc
a bei bian yi wei bu ma
調試看了下結果如下:

[root@localhost dry]# gdb cc
GNU gdb Fedora (6.8-29.fc10)
Copyright (C) 2008 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i386-redhat-linux-gnu"...
(gdb) list
1 #include <stdio.h>
2 int main()
3 {
4 size_t a=-1;
5 size_t b=90;
6 if (a<b)
7 printf("a bao chi bu bian/n");
8 else
9 printf("a bei bian yi wei bu ma/n");
10 }
(gdb) b 6
Breakpoint 1 at 0x80483d3: file cc.c, line 6.
(gdb) run
Starting program: /home/spexamples/1/5/dry/cc

Breakpoint 1, main () at cc.c:6
6 if (a<b)
Missing separate debuginfos, use: debuginfo-install glibc-2.9-2.i686
(gdb) print a
$1 = 4294967295
(gdb) print b
$2 = 90
(gdb) s
9 printf("a bei bian yi wei bu ma/n");
(gdb) s
a bei bian yi wei bu ma
10 }
由此可以看出,在編譯的過程中size_t類型的a值會被編譯他的補碼。所以在使用size_t類型數據的過程中尤其要注意,特別是在邏輯表達式中使用到該類型,稍不注意可能帶來很嚴重的後果。

注:正數的補碼:與原碼相同;負數的補碼:符號位爲1,其餘位爲該數絕對值的原碼按位取反,然後整個數加1

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章