Skip to content

Commit

Permalink
Merge pull request #476 from katef/kate/xstrndup
Browse files Browse the repository at this point in the history
Add xstrndup
  • Loading branch information
katef authored May 31, 2024
2 parents e6ba81b + 825a621 commit 2483417
Show file tree
Hide file tree
Showing 9 changed files with 270 additions and 324 deletions.
11 changes: 6 additions & 5 deletions include/adt/xalloc.h
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2008-2017 Katherine Flavel
* Copyright 2008-2024 Katherine Flavel
*
* See LICENCE for the full copyright terms.
*/
Expand All @@ -8,21 +8,22 @@
#define XALLOC_H

/*
* Duplicate a string. Returns NULL on error.
* These functions are for CLI use only; they exit on error
*/

char *
xstrdup(const char *s);

/*
* The following functions are for CLI use only; they exit on error
*/
char *
xstrndup(const char *s, size_t n);

void *
xmalloc(size_t sz);

void *
xcalloc(size_t count, size_t sz);

/* equivalent to free(p) when sz is 0, returns NULL */
void *
xrealloc(void *p, size_t sz);

Expand Down
20 changes: 15 additions & 5 deletions src/adt/xalloc.c
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2008-2017 Katherine Flavel
* Copyright 2008-2024 Katherine Flavel
*
* See LICENCE for the full copyright terms.
*/
Expand All @@ -24,6 +24,19 @@ xstrdup(const char *s)
return strcpy(new, s);
}

char *
xstrndup(const char *s, size_t n)
{
char *new;

new = malloc(n);
if (new == NULL) {
return NULL;
}

return memcpy(new, s, n);
}

void *
xmalloc(size_t sz)
{
Expand Down Expand Up @@ -57,11 +70,8 @@ xrealloc(void *p, size_t sz)
{
void *q;

/* This is legal and frees p, but confusing; use free() instead */
assert(sz != 0);

q = realloc(p, sz);
if (q == NULL) {
if (sz > 0 && q == NULL) {
perror("realloc");
abort();
}
Expand Down
10 changes: 2 additions & 8 deletions src/libfsm/parser.act
Original file line number Diff line number Diff line change
Expand Up @@ -241,11 +241,8 @@
@};

IDENT: () -> (s :string) = @{
/* XXX: don't exit in library code */
@s = xstrdup(lex_state->buf.a);
if (@s == NULL) {
perror("xstrdup");
exit(EXIT_FAILURE);
}
@};

%actions%
Expand Down Expand Up @@ -288,11 +285,8 @@
exit(EXIT_FAILURE);
}

/* XXX: don't exit in library code */
new->id = xstrdup(@n);
if (new->id == NULL) {
perror("xstrdup");
exit(EXIT_FAILURE);
}

if (!fsm_addstate(fsm, &@s)) {
perror("fsm_addstate");
Expand Down
Loading

0 comments on commit 2483417

Please sign in to comment.