Cosmetic improvements.
[usmb.git] / utils.c
blob597bd3d8d48676bd4f794dc9fe9ce4d70199f218
1 /* usmb - mount SMB shares via FUSE and Samba
2 * Copyright (C) 2006-2008 Geoff Johnstone
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 3 as
6 * published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 #include <assert.h>
18 #include <stdarg.h>
19 #include <stddef.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include "utils.h"
27 #define INIT_LEN 256
28 char * concat_strings (int num, ...)
30 va_list ap;
32 char *base, *out;
34 base = out = malloc (INIT_LEN);
35 if (NULL == base)
36 return NULL;
38 size_t buff_size = INIT_LEN;
40 va_start (ap, num);
41 for (int i = 0; i < num; ++i)
43 const char *next = va_arg (ap, const char *);
44 assert (NULL != next);
46 size_t next_len = strlen (next);
47 /*LINTED*/
48 size_t required = (out - base) + next_len + 1;
50 if (buff_size < required)
52 while (buff_size < required)
54 size_t dbl_len = buff_size * 2;
55 if (dbl_len < buff_size)
57 free (base);
58 return NULL;
61 buff_size = dbl_len;
64 /*LINTED*/
65 ptrdiff_t diff = out - base;
67 char *newbase = realloc (base, buff_size);
68 if (NULL == newbase)
70 free (base);
71 return NULL;
74 base = newbase;
75 out = base + diff;
78 memcpy (out, next, next_len);
79 out += next_len;
81 va_end (ap);
83 *out = '\0';
84 return base;
88 char * xstrdup (const char *in)
90 char *out = NULL;
92 if (in)
94 size_t len = strlen (in) + 1;
96 if ((out = malloc (len)))
97 memcpy (out, in, len);
100 return out;
104 // the const here lets us pass a pointer to const
105 void xfree (const void *ptr)
107 if (NULL != ptr)
108 free ((void *)ptr);
112 void clear_and_free (char *ptr)
114 if (NULL != ptr)
116 for (char *pch = ptr; '\0' != *pch; ++pch)
117 *pch = '\0';
119 free (ptr);