#include <stdio.h>    // for printf
#include <stdlib.h>   // for getenv, malloc, free
#include <string.h>   // for strtok, strcpy

#define MAX_PATHS 100
char * searchpaths[MAX_PATHS];

void tokenize_PATH();
void print_PATH();
void free_PATH();

int main()
{
  tokenize_PATH();
  print_PATH();
  free_PATH();

  exit(EXIT_SUCCESS);
}

void tokenize_PATH()
{
  char *s, *token;
  char *pathbuf;
  int i = 0;

  s = getenv("PATH");

  if (s == NULL)
  {
    printf("PATH variable not found\n");
    return;
  }

  /* Make a local copy of the PATH value */
  /* This is necessary to keep the environment unaltered */ 
  pathbuf = malloc(strlen(s)+1);
  strcpy(pathbuf, s);

  /* Tokenize the local copy of the PATH string */
  token = strtok(pathbuf, ":");
  while((token != NULL) && (i < MAX_PATHS-1))
  {
    /* allocate memory for the new token */
    searchpaths[i] = malloc(strlen(token)+1);

    /* copy the token into the newly allocated memory */
    strcpy(searchpaths[i], token);

    /* retrieve the next token (if any) */
    token = strtok(NULL, ":");
    i++;
  }
  /* Mark the end of the search paths in the array */
  searchpaths[i] = NULL;

  free(pathbuf);   /* no longer necessary */
}

void print_PATH()
{
  int i;

  for(i = 0; searchpaths[i] != NULL; i++)
    printf("%s\n", searchpaths[i]);
}

void free_PATH()
{
  int i;

  for(i = 0; searchpaths[i] != NULL; i++)
  {
    free(searchpaths[i]);
    searchpaths[i] = NULL;
  }
}