- 论坛徽章:
- 0
|
原帖由 飞灰橙 于 2008-7-11 23:12 发表 ![]()
确信这样写不会有内存泄露?
--------------------------------------------------------------------------------------------------------------
/*
* split.c
* 利用glib库实现的 split 函数功能
* veking
* 2008-07-11
*/
#include <stdio.h>
#include <glib.h>
GPtrArray *split(GPtrArray *a, char *s, const char *t, size_t n);
int main(void)
{
int i;
char *str = "one,two,three,monday,sunday";
GPtrArray *arr = g_ptr_array_new();
split(arr, str, ",", 32);
for(i = 0; i < arr->len; i++){
fprintf(stdout, "item[%d]: %s\n", i, g_ptr_array_index(arr, i));
}
g_ptr_array_free(arr, TRUE);
return 0;
}
/*
* split
* a 字符串分割后的指针数组
* s 是要进行分割的字符串,分割后值被改变,如果不想改变其值,请自行修改
* t 是字符串的分隔符号
* n 是数组元素的缓冲区大小
*/
GPtrArray *split(GPtrArray *a, char *s, const char *t, size_t n)
{
char *p = NULL;
char *buf = NULL;
buf = (char *)malloc(n);
if(!buf){
fprintf(stderr, "malloc error!\n");
exit(1);
}
while((p = strpbrk(s, t))){
strncpy(buf, s, p - s);
g_ptr_array_add(a, strdup(buf));
s += p - s + strlen(t);
memset(buf, 0, sizeof(buf));
}
if(s)
g_ptr_array_add(a, strdup(s));
free(buf);
}
[ 本帖最后由 veking 于 2008-7-12 00:33 编辑 ] |
|