C 语言实现动态字符串

在C语言中,字符串是以连续的字节流表示的,并且以 '\0' 结尾,C语言标准库中也提供了很多函数来操作这种形式的字符串,比如,求字符串长度 strlen( ),求子串strstr( ),字符串拷贝strcpy( )等等,但是,这些函数并不安全,很可能给系统或应用程序带来严重的问题,如栈溢出等,C语言字符串中并没有记录操作系统为其分配的长度,用户必须自己将字符串长度保存在其他的变量中,很明显如果操作不当就会产生错误,如臭名昭著的缓冲区溢出。

其他语言中的字符串类型通常在存储字符串本身时也保存了字符串长度,如Pascal,这样做的好处是字符串也可以以空字符'\0'结尾,但也会产生缓冲区溢出错误,本文实现了一个简单的动态字符串库,首先考虑一下,采用什么样的数据结构可以避免缓冲区溢出问题呢,为简化起见,我们定义“字符串”为内存中无类型的字节流,因此可以避开本地化和Unicode等概念,首先定义数据结构如下:

 1 #ifndef __DSTRING_H
2 #define __DSTRING_H
3
4 typedef struct _dstring dstring;
5 struct _dstring
6 {
7 char *pstr;
8 size_t str_sz;
9 size_t buf_sz;
10 };
11 #endif

pstr 是指向字符串的指针,str_sz 是字符串长度,而 buf_sz则是包含该字符串的缓冲区长度。

接下来一个问题就是为字符串分配存储空间,由于内存分配可能失效,所以我们需要检查内存分配是否成功,一种可行的方法是在分配函数中返回错误码,但是,这样设计的API不太简洁实用,另外一个可选方案是事先注册一个回调函数,在内存分配失败时再调用该函数,但如果多个客户程序同时申请内存,该方法也会失效,C++中我们可以使用异常来处理这种情况,但是 C 不支持异常,所以该方法也不太现实。其实,某些其他的标准库代码也有类似的问题,如数学库中某个函数对一个负数进行求根运算,返回结果本来是double,为了表明函数调用出错,我们可以让函数返回NaN(Not a Number),因此程序在需要检查该函数调用是否出错时可以检查返回值。

我们也采用与此类似的方法,如果内存分配出错,那么动态字符串返回NaS(Not a String)状态,任何返回NaS的操作将维护该状态,因此程序只需要在必要的时候检查其返回值,为了实现该效果,我们可以定义如下的宏,

1 #define NaS ((string) {NULL, 0, 0})
2 #define isnas(S) (!(S)->pstr)
3
4 static size_t dstr_size(dstring *s)
5 {
6 if (isnas(s)) return 0;
7 return pstr->str_sz;
8 }

接下来的问题是字符串指针可能指向不同的位置,例如,可以是在编译时刻就确定的静态区,也可以栈中的某个位置,还可以只由malloc或realloc函数分配动态内存区(堆区),只有在堆区分配的内存才能够被resize,即realloc( ),并且需要显式地free( ),因此我们需要记录字符串指向区域的类型,我们选择了 buf_sz 的高位来保存该状态,基于以上想法,我们如下定义内存分配函数:

 1 #define DSTR_FREEABLE (1ULL << 63)
2 /* An initialized empty struct string */
3 #define DSTR_INIT ((string) {malloc(16), 0, (16)})
4
5 static dstring dstr_malloc(size_t size)
6 {
7 if (size < 16) size = 16;
8 return (dstring) {malloc(size), 0, size | DSTR_FREEABLE};
9 }
10
11 /* Try to compact string memory */
12 static void dstr_realloc(dstring *s)
13 {
14 char *buf;
15
16 /* Not a string? */
17 if (isnas(s)) return;
18
19 /* Can't realloc? */
20 if (!(s->buf_sz & DSTR_FREEABLE)) return;
21
22 /* Don't invoke undefined behaviour with realloc(x, 0) */
23 if (!s->str_sz){
24 free(s->pstr);
25 s->pstr = malloc(16);
26 } else {
27 /* Try to compact */
28 buf = realloc(s->pstr, s->str_sz);
29 if (buf) s->pstr = buf;
30 }
31 }
32
33 static void dstr_resize(dstring *s, size_t size)
34 {
35 char *buf;
36 size_t bsize;
37
38 /* Are we not a string? */
39 if (isnas(s)) return;
40
41 /* Not resizable */
42 if (!(s->buf_sz & DSTR_FREEABLE)) {
43 dstring s2;
44
45 /* Don't do anything if we want to shrink */
46 if (size <= s->str_sz) return;
47
48 /* Need to alloc a new string */
49 s2 = dstr_malloc(size);
50
51 /* Copy into new string */
52 memcpy(s2.pstr, s->pstr, s->str_sz);
53
54 /* Point to new string */
55 s->pstr = s2.pstr;
56 s->buf_sz = s2.buf_sz;
57 return;
58 }
59
60 /* Too big */
61 if (size & DSTR_FREEABLE)
62 {
63 free(s->pstr);
64 *s = NaS;
65 return;
66 }
67
68 bsize = s->buf_sz - DSTR_FREEABLE;
69
70 /* Keep at least 16 bytes */
71 if (size < 16) size = 16;
72
73 /* Nothing to do? */
74 if ((4 * size > 3 * bsize) && (size <= bsize)) return;
75
76 /* Try to double size instead of using a small increment */
77 if ((size > bsize) && (size < bsize * 2)) size = bsize * 2;
78
79 /* Keep at least 16 bytes */
80 if (size < 16) size = 16;
81
82 buf = realloc(s->pstr, size);
83
84 if (!buf) {
85 /* Failed, go to NaS state */
86 free(s->pstr);
87 *s = NaS;
88 } else {
89 s->pstr = buf;
90 s->buf_sz = size | DSTR_FREEABLE;
91 }
92 }
93
94 static void dstr_free(dstring *s)
95 {
96 if (s->buf_sz & DSTR_FREEABLE) free(s->pstr);
97
98 *s = NaS;
99 }

有了以上的函数,我们可以定义如下宏,以便将C风格的字符串转换为我们的动态字符串,

 1 /*
2 * Copy a struct dstring to the stack.
3 * (Could use strdupa(), but this is more portable)
4 */
5 #define dstr_dupstr_aux(S)\
6 __extension__ ({\
7 char *_stradupstr_aux = alloca((S).str_sz + 1);\
8 memcpy(_stradupstr_aux, (S).pstr, (S).str_sz);\
9 dstr_straux(_stradupstr_aux, (S).str_sz);\
10 })
11
12 #define dstr_adupstr(S) dstr_dupstr_aux(*(S))
13
14 /* A struct dstring based on a C string, stored on the stack */
15 #define S(C) dstr_dupstr_aux(dstr_cstr((char *)C))
16
17 static dstring dstr_straux(char *c, size_t len)
18 {
19 return (dstring) {c, len, len + 1};
20 }
21
22 /* A struct dstring based on a C string, stored in whatever c points to */
23 static dstring dstr_cstr(char *c)
24 {
25 size_t len = strlen(c);
26 return dstr_straux(c, len);
27 }

上述代码中的宏S(C)使用了alloca在栈上分配空间,这意味着该空间不需要显示的释放,在函数退出时将自动被系统回收。

大多数时候,字符串分配在栈中,但是,有时候我们也需要将字符串保存在生命周期更长的结构中,此时,我们就需要显式地为字符串分配空间:

 1 /* Create a new dstring as a copy of an old one */
2 static dstring dstr_dupstr(dstring *s)
3 {
4 dstring s2;
5
6 /* Not a string? */
7 if (isnas(s)) return NaS;
8
9 s2 = dstr_malloc(s->str_sz);
10 s2.str_sz = s->str_sz;
11 memcpy(s2.pstr, s->pstr, s->str_sz);
12
13 return s2;
14 }
15
16 /* Copy the memory from the source string into the dest string */
17 static void dstr_cpystr(dstring *dest, dstring *src)
18 {
19 /* Are we no a string */
20 if (isnas(src)) return;
21
22 dstr_resize(dest, src->str_sz);
23
24 if (isnas(dest)) return;
25 dest->str_sz = src->str_sz;
26 memcpy(dest->pstr, src->pstr, src->str_sz);
27 }

当然,既然C语言标准库使用以Null结尾的字符串,我们需要将动态字符串转换成C风格的字符串,如下:

 1 static char *dstr_tocstr(dstring *s)
2 {
3 size_t bsize;
4
5 /* Are we not a string? */
6 if (isnas(s)) return NULL;
7
8 /* Get real buffer size */
9 bsize = s->b_str_sz & ~DSTR_FREEABLE;
10
11 if (s->str_sz == bsize){
12 /* Increase buffer size */
13 dstr_resize(s, bsize + 1);
14 /* Are we no longer a string? */
15 if (isnas(s)) return NULL;
16 }
17
18 /* Tack a zero on the end */
19 s->pstr[s->str-sz] = 0;
20 /* Don't update the size */
21 /* Can use this buffer as long as you don't append anything else */
22 return s->pstr;
23 }

当然,上面的所讲的内容并没有完全解决缓冲区溢出的问题,因此,我们可以定义一下的宏来进行边界检查,

 1 #ifdef DEBUG_CHECK_BOUNDS
2 #define S_C(S, I)\
3 (* __extension__ ({\
4 assert((I) >= 0);\
5 assert((I) < (S)->str_sz);\
6 assert((I) < ((S)->buf_sz & ~DSTR_FREEABLE));\
7 &((S)->s[I]);\
8 }))
9 #else
10 #define S_C(S, I) ((S)->s[I])
11 #endif

接下来的任务是向动态字符串中追加新的C类型的字符串,

 1 static void dstr_ncatcstr(dstring *s, size_t len, const char *str)
2 {
3 size_t bsize;
4
5 /* Are we not a string? */
6 if (isnas(s)) return;
7
8 /* Nothing to do? */
9 if (!str || !len) return;
10
11 /* Get real buffer size */
12 bsize = s->buf_sz & ~DSTR_FREEABLE;
13
14 if (s->str_sz + len >= bsize)
15 {
16 dstr_resize(s, s->str_sz + len);
17
18 /* Are we no longer a string? */
19 if (isnas(s)) return;
20 }
21
22 memcpy(&s->pstr[s->str_sz], str, len);
23 s->str_sz += len;
24 }
25
26 static void dstr_catcstr(dstring *s, const char *str)
27 {
28 if (str) dstr_ncatcstr(s, strlen(str), str);
29 }
30
31 static void dstr_catstr(dstring *s, const dstring *s2)
32 {
33 dstr_ncatcstr(s, s2->str_sz, s2->pstr);
34 }
35
36 static void dstr_catcstrs(dstring *s, ...)
37 {
38 const char *str;
39 va_list v;
40
41 /* Are we not a string? */
42 if (isnas(s)) return;
43
44 va_start(v, s);
45
46 for (str = va_arg(v, const char *); str; str = va_arg(v, const char *))
47 {
48 dstr_ncatcstr(s, strlen(str), str);
49 }
50
51 va_end(v);
52 }
53
54 static void dstr_catstrs(dstring *s1, ...)
55 {
56 const dstring *s2;
57 va_list v;
58
59 /* Are we not a string? */
60 if (isnas(s1)) return;
61
62 va_start(v, s1);
63
64 for (s2 = va_arg(v, const dstring *); s2; s2 = va_arg(v, const dstring *)) {
65 dstr_ncatcstr(s1, s2->str_sz, s2->pstr);
66 }
67
68 va_end(v);
69 }

最后容易出现缓冲区溢出情况是格式化输入,由于不知道输入串长度,所以使用sprintf( ) 函数也比较容易出错(本地化),snprintf( ) 能够解决该问题,但是输出缓冲区太小了,很容易被截断,

 1 static void dstr_printf(dstring *s, const char *fmt, ...)
2 {
3 va_list v;
4 size_t len;
5
6 /* Are we not a string? */
7 if (isnas(s)) *s = DSTR_INIT;
8
9 /* Nothing to do? */
10 if (!fmt) return;
11
12 va_start(v, fmt);
13 len = vsnprintf(NULL, 0, fmt, v) + 1;
14 va_end(v);
15
16 dstr_resize(s, len);
17
18 /* Are we no longer a string? */
19 if (isnas(s)) return;
20
21 va_start(v, fmt);
22 vsnprintf(s->s, len, fmt, v);
23 va_end(v);
24 s->str_sz = len - 1;
25 }

最后,我们经常在栈中分配格式化字符,以下函数可以将结果打印至屏幕会文件,

1 /* Use a (C string) format and return a stack-allocated struct dstring */
2 #define straprintf(...)\
3 __extension__ ({\
4 size_t _straprintf_len = snprintf(NULL, 0, __VA_ARGS__) + 1;\
5 char *_straprintf_buf = alloca(_straprintf_len);\
6 snprintf(_straprintf_buf, _straprintf_len, __VA_ARGS__);\
7 dstr_straux(_straprintf_buf, _straprintf_len - 1);\
8 })

至此,动态字符串的大部分API已经介绍完毕,使用上面所讲的函数和宏将会大大减少缓冲区溢出的危险,因此推荐各位同学在实际需要中使用上述的函数和宏。(完)





原文地址:https://www.cnblogs.com/haippy/p/2290494.html