source: libabac/abac_util.c @ f2622ee

abac0-leak
Last change on this file since f2622ee was f2622ee, checked in by Mei-Hui Su <mei@…>, 11 years ago

1) ran with valgrind and did some leak patching

  • Property mode set to 100644
File size: 2.0 KB
Line 
1
2/* abac_util.c */
3
4#include <err.h>
5#include <stdlib.h>
6#include <string.h>
7#include <assert.h>
8#include <ctype.h>
9
10#include <abac_util.h>
11
12/**
13 * Malloc, fatal on error.
14 */
15void *abac_xmalloc(size_t size) {
16    void *ret;
17   
18    ret = malloc(size);
19    if (ret == NULL)
20        err(1, "malloc");
21
22    return ret;
23}
24
25void abac_chunk_free(abac_chunk_t chunk)
26{
27   if(chunk.len)
28       free(chunk.ptr);
29   chunk.len=0;
30   chunk.ptr=NULL;
31}
32
33/**
34 * strdup fatal on error
35 */
36char *abac_xstrdup(char *source) {
37    char *ret;
38
39    if (source == NULL)
40        return NULL;
41
42    ret = strdup(source);
43    if (ret == NULL)
44        err(1, "strdup");
45
46    return ret;
47}
48
49void *abac_xrealloc(void *ptr, size_t size) {
50    void *ret = realloc(ptr, size);
51    if (ret == NULL)
52        err(1, "couldn't realloc %zu bytes\n", size);
53    return ret;
54}
55
56/**
57 * Split a string based on the given delimiter.  The substrings are pointers
58 * into string, which has string terminators added to slice it into substrings.
59 * Do not free the returned substrings.  num passes in the maximum number of
60 * substrings to create and is returned as the number actually created.
61 */
62#define MAXSPLIT    1024
63void abac_split(char *string, char *delim, char **ret, int *num) {
64    int len = strlen(delim);
65    char *start = string;
66    int count = 0;
67    int lim = (num && *num > 0) ? *num : MAXSPLIT;
68
69    // split the string by the delim.  Split into at most lim parts
70    while ((start = strstr(string, delim)) != NULL && count < lim-1) {
71        *start = 0;
72        ret[count++] = string;
73        string = start + len;
74    }
75    ret[count++] = string;
76
77    *num = count;
78}
79
80int abac_clean_name(char *string) {
81    int i;
82
83    assert(string != NULL);
84
85    // must start with a letter/number
86    if (!isalnum(string[0])) return 0;
87
88    // Name must be alphanumeric or - or _ or :
89    for (i = 1; string[i] != '\0'; ++i)
90        if (!isalnum(string[i]) && string[i] != '-' && string[i] != '_' &&
91                string[i] != ':')
92            return 0;
93
94    return 1;
95}
96
Note: See TracBrowser for help on using the repository browser.