Skip to content

Commit 6947d6b

Browse files
Cropistevegrubb
authored andcommitted
Custom strndupa: Convert it to a macro instead of a function (#385)
* Custom strndupa: Convert it to a macro instead of a function Looking at https://www.gnu.org/software/libc/manual/html_node/Truncating-Strings.html , strndupa is implemented as a macro. It uses malloca, which allocates space in the stack frame of the caller. The temporary space is automatically freed when the function that called alloca returns. * Remove extra () from strndupa macro
1 parent a5f87a5 commit 6947d6b

File tree

2 files changed

+18
-16
lines changed

2 files changed

+18
-16
lines changed

auparse/auparse.c

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -502,7 +502,7 @@ auparse_state_t *auparse_init(ausource_t source, const void *b)
502502
if (access_ok(b))
503503
goto bad_exit;
504504
tmp = malloc(2*sizeof(char *));
505-
if (tmp == NULL)
505+
if (tmp == NULL)
506506
goto bad_exit;
507507
tmp[0] = strdup(b);
508508
tmp[1] = NULL;
@@ -1215,13 +1215,14 @@ static int str2event(char *s, au_event_t *e)
12151215
}
12161216

12171217
#ifndef HAVE_STRNDUPA
1218-
static inline char *strndupa(const char *old, size_t n)
1219-
{
1220-
size_t len = strnlen(old, n);
1221-
char *tmp = alloca(len + 1);
1222-
tmp[len] = 0;
1223-
return memcpy(tmp, old, len);
1224-
}
1218+
#define strndupa(s, n) \
1219+
({ \
1220+
const char *__old = (s); \
1221+
size_t __len = strnlen (__old, (n)); \
1222+
char *__new = (char *) alloca(__len + 1); \
1223+
__new[__len] = '\0'; \
1224+
(char *) memcpy (__new, __old, __len); \
1225+
})
12251226
#endif
12261227

12271228
/* Returns 0 on success and 1 on error */

src/ausearch-lol.c

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -163,13 +163,14 @@ static int compare_event_time(event *e1, event *e2)
163163
}
164164

165165
#ifndef HAVE_STRNDUPA
166-
static inline char *strndupa(const char *old, size_t n)
167-
{
168-
size_t len = strnlen(old, n);
169-
char *tmp = alloca(len + 1);
170-
tmp[len] = 0;
171-
return memcpy(tmp, old, len);
172-
}
166+
#define strndupa(s, n) \
167+
({ \
168+
const char *__old = (s); \
169+
size_t __len = strnlen (__old, (n)); \
170+
char *__new = (char *) alloca(__len + 1); \
171+
__new[__len] = '\0'; \
172+
(char *) memcpy (__new, __old, __len); \
173+
})
173174
#endif
174175

175176
/*
@@ -244,7 +245,7 @@ static int extract_timestamp(const char *b, event *e)
244245
return 0;
245246
}
246247

247-
// This function will check events to see if they are complete
248+
// This function will check events to see if they are complete
248249
// FIXME: Can we think of other ways to determine if the event is done?
249250
static void check_events(lol *lo, time_t sec)
250251
{

0 commit comments

Comments
 (0)