home *** CD-ROM | disk | FTP | other *** search
- /* stov.c -- convert string to vector
- Copyright (C) 1989 David MacKenzie
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 1, or (at your option)
- any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
-
- #include "hint.h"
-
- /* Number of arguments between realloc's. */
- #define GRANULARITY 10
-
- /* Make an argv-like vector (string array) from string `s' (such as an
- environment variable). The last element of the vector is null.
- Return a static structure with a malloc'd array of pointers into `s'.
- Scatters nulls throughout `s'. */
-
- struct args *
- stov (s)
- char *s;
- {
- static struct args args;
- int argc;
- char **argv;
-
- argc = 0;
- argv = (char **) xmalloc ((unsigned) (sizeof (char *) * GRANULARITY));
-
- for (s = strtok (s, " \t\n\r"); s; s = strtok ((char *) NULL, " \t\n\r"))
- {
- if (argc > 0 && argc % GRANULARITY == 0)
- argv = (char **) xrealloc ((char *) argv,
- (unsigned) (sizeof (char *) * (argc + GRANULARITY)));
- argv[argc++] = s;
- }
- argv = (char **) xrealloc ((char *) argv,
- (unsigned) (sizeof (char *) * (argc + 1)));
- argv[argc] = NULL;
- args.argc = argc;
- args.argv = argv;
- return &args;
- }
-
- static void
- memory_out ()
- {
- fprintf (stderr, "%s: Virtual memory exhausted\n", program_name);
- exit (1);
- }
-
- /* Allocate `n' bytes of memory dynamically, with error checking. */
-
- char *
- xmalloc (n)
- unsigned n;
- {
- char *p;
-
- p = malloc (n);
- if (p == 0)
- memory_out ();
- return p;
- }
-
- /* Change the size of an allocated block of memory `p' to `n' bytes,
- with error checking.
- If `p' is NULL, run xmalloc.
- If `n' is 0, run free and return NULL. */
-
- char *
- xrealloc (p, n)
- char *p;
- unsigned n;
- {
- if (p == 0)
- return xmalloc (n);
- if (n == 0)
- {
- free (p);
- return 0;
- }
- p = realloc (p, n);
- if (p == 0)
- memory_out ();
- return p;
- }
-