Thursday, April 25, 2013

Split functionality of awk implementation in C


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include "stdio.h"
#include "stdlib.h"
#include "string.h"

static unsigned split(const char *in, char ***t_out, const char *delim)
{

        if( !*in || !*delim ){
                return 0;
        }

        unsigned i_len = strlen(in);
        char *buf = NULL;
        char *ptr = NULL;
        unsigned t_len, i=0;

        buf = malloc(sizeof(char) * i_len);
        if(!buf) return 0;

        if(!memcpy(buf, in, i_len)) return 0;

        ptr = strtok(buf, delim);
        if(ptr) {
                t_len = strlen(ptr);
                *t_out = (char **)malloc(sizeof(char*));
                (*t_out)[0] = (char *)malloc(sizeof(char) * t_len);
                memcpy((*t_out)[0], ptr, t_len);
        }
        while(ptr){
                ptr = strtok(NULL, delim);
                if(ptr) {
                        i++;
                        t_len = strlen(ptr);
                        *t_out = (char **)realloc(*t_out, sizeof(char *) * (i+1));
                        (*t_out)[i] = (char *)malloc(sizeof(char) * t_len);
                        memcpy((*t_out)[i], ptr, t_len);
                }
        }
        free(buf);
        return i;
}

int main(int argc, char **argv)
{

        char *in = "split.implementation.of.awk";
        char **out = NULL;
        int i, len = split(in, &out, ".");

        if(out) {
                for(i=0; i<=len; i++){
                        printf("%s\n", out[i]);
                        free(out[i]);
                }
                free(out);
        }
        return 0;
}


[root@Imperfecto_1 ~] gcc -g run.c && ./a.out
split
implementation
of
awk

Valgrind output

[root@Imperfecto_1 ~]# valgrind ./a.out
==2320== malloc/free: in use at exit: 0 bytes in 0 blocks.
==2320== malloc/free: 9 allocs, 9 frees, 91 bytes allocated.
==2320== For counts of detected errors, rerun with: -v
==2320== All heap blocks were freed -- no leaks are possible.

No comments:

Post a Comment