看完陳皓的C/C++返回內(nèi)部靜態(tài)成員的陷阱,認(rèn)識(shí)到自己確實(shí)對(duì)C/C++本身語(yǔ)法研究的不夠清楚,所以這些時(shí)間就在對(duì)基本知識(shí)進(jìn)行回顧,真的還蠻有意思的。
我在用C/C++函數(shù)時(shí),從沒(méi)有全面考慮過(guò)該函數(shù)功能,只是知道它能做,基本對(duì)函數(shù)細(xì)節(jié)沒(méi)有了解,就拿下面這個(gè)函數(shù)做個(gè)例子:
char *inet_ntoa(struct in_addr in);
struct in_addr { unsigned long int s_addr; }
看到這個(gè)我就能想到該函數(shù)是把一個(gè)unsigned long type的數(shù)轉(zhuǎn)換成一個(gè)字符串。其它什么都不想。現(xiàn)在讓我們來(lái)仔細(xì)品讀里面的東西。
我傳入一個(gè)unsigned long type的數(shù)據(jù),它給我傳出一個(gè)char *,那這個(gè)char * 在函數(shù)里怎么分配空間的。首先不可能是堆分配,因?yàn)槿绻悄菢拥脑挘阌猛赀@個(gè)函數(shù)后還要釋放資源。其次不可能是棧分配,因?yàn)槟菢雍瘮?shù)返回后棧也會(huì)跟著釋放。那還有可能是全局變量,如果這樣的話,C/C++中已經(jīng)有好多全局了。那還有一種是static的可能,static不會(huì)隨著函數(shù)的返回而釋放,也就是說(shuō),它是一塊長(zhǎng)期被分配的內(nèi)存空間,現(xiàn)在在假若我在程序中這樣寫(xiě):
printf(“%s, %s”, inet_ntoa(a), inet_ntoa(b)); //a, b 是兩個(gè)不相等的值
輸出會(huì)讓我大吃一驚,輸出結(jié)果一樣。原因很簡(jiǎn)單,就是printf先求b,把值給了那個(gè)static,然后再求a, 把值又給了static,static的那塊內(nèi)存最終被寫(xiě)入了a的值,這個(gè)時(shí)候輸出,那當(dāng)然就輸出的同一個(gè)值了。還有一種錯(cuò)誤寫(xiě)法,如下:
Char *tmp1 = inet_ntoa(a);
Char *tmp2 = inet_ntoa(b);
這樣也是有問(wèn)題的,因?yàn)?/span>tmp1和tmp2都指向了一塊內(nèi)存,當(dāng)前的static的值就是b的值了。所以總結(jié)如下,使用這種函數(shù)一定要copy函數(shù)返回的值,而不能去保存其內(nèi)存地址!
附inet_ntoa()源碼:
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <bits/libc-lock.h>
/* The interface of this function is completely stupid, it requires a
static buffer. We relax this a bit in that we allow at least one
buffer for each thread. */
/* This is the key for the thread specific memory. */
static __libc_key_t key;
/* If nonzero the key allocation failed and we should better use a
static buffer than fail. */
static char local_buf[18];
static char *static_buf; //靜態(tài)
/* Destructor for the thread-specific data. */
static void init (void);
static void free_key_mem (void *mem);
char *
inet_ntoa (struct in_addr in)
{
__libc_once_define (static, once);
char *buffer;
unsigned char *bytes;
/* If we have not yet initialized the buffer do it now. */
__libc_once (once, init);
if (static_buf != NULL)
buffer = static_buf;
else
{
/* We don't use the static buffer and so we have a key. Use it
to get the thread-specific buffer. */
buffer = __libc_getspecific (key);
if (buffer == NULL)
{
/* No buffer allocated so far. */
buffer = malloc (18);
if (buffer == NULL)
/* No more memory available. We use the static buffer. */
buffer = local_buf;
else
__libc_setspecific (key, buffer);
}
}
bytes = (unsigned char *) ∈
__snprintf (buffer, 18, "%d.%d.%d.%d",
bytes[0], bytes[1], bytes[2], bytes[3]);
return buffer;
}
/* Initialize buffer. */
static void
init (void)
{
if (__libc_key_create (&key, free_key_mem))
/* Creating the key failed. This means something really went
wrong. In any case use a static buffer which is better than
nothing. */
static_buf = local_buf;
}