星期一, 1月 19, 2009

NULL to strlen function

當我們對某個指標做 strlen,且該指標指向 NULL 時,例如:
char *ptr = NULL
printf("string length : %d\n", strlen(ptr));

會產生
Segmentation fault

因為:
http://bytes.com/groups/c/586992-null-strlen-function#post2303741
You're apparently a new programmer, so let me add this:

A NULL pointer and a string of length zero are not the same thing.

A NULL pointer traditionally has the value of 0, which is usually an
unsuitable pointer; but in any case it is a reserved value defined to be a
non-functional pointer.

A string of length 0 has a non-NULL pointer, but the area of memory that is
pointed to has its first byte as 0.

The two are very different.

解法是先檢查指標是否為 NULL:
char *ptr = NULL;
if(ptr != NULL)
printf("string length : %d\n", strlen(ptr));
else
printf("string is a NULL string\n");

沒有留言: