fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5.  
  6. struct nlist {
  7. struct nlist *next;
  8. char *name;
  9. char *defn;
  10. };
  11.  
  12. #define HASHSIZE 101
  13. static struct nlist *hashtab[HASHSIZE];
  14.  
  15. unsigned hash (char *s)
  16. {
  17. unsigned hashval;
  18.  
  19. for (hashval = 0; *s != '\0'; s++)
  20. hashval += *s + 31 * hashval;
  21. return hashval % HASHSIZE;
  22. }
  23.  
  24. struct nlist * lookup (char *s)
  25. {
  26. struct nlist *np;
  27.  
  28. for (np = hashtab[hash(s)]; np != NULL; np = np->next)
  29. if (strcmp(s, np->name) == 0)
  30. return np;
  31. return NULL;
  32. }
  33.  
  34. struct nlist * install (char *name, char *defn)
  35. {
  36. struct nlist *np;
  37. unsigned hashval;
  38.  
  39. if ((np = lookup(name)) == NULL)
  40. {
  41. np = (struct nlist *) malloc(sizeof(*np));
  42. if (np == NULL || (np->name = strdup(name)) == NULL)
  43. return NULL;
  44. hashval = hash(name);
  45. np->next = hashtab[hashval];
  46. hashtab[hashval] = np;
  47. }
  48. else
  49. free ((void *) np->defn);
  50. if ((np->defn = strdup(defn)) == NULL)
  51. return NULL;
  52. return np;
  53. }
  54.  
  55. void undef (char *name)
  56. {
  57. struct nlist *curr, *last;
  58. unsigned hashval;
  59.  
  60. last = curr = hashtab[hash(name)];
  61. while (curr != NULL && strcmp(name, curr->name)!= 0)
  62. {
  63. printf("while loop\n");
  64. last = curr;
  65. curr = curr->next;
  66. printf("last = %x, curr = %x\n", last, curr);
  67. }
  68.  
  69. printf("after loop\n");
  70. if (curr)
  71. {
  72. last->next = curr->next;
  73. // !!!!!!!!
  74. free (curr);
  75. free ((void *) curr->name);
  76. free ((void *) curr->defn);
  77. }
  78. }
  79.  
  80.  
  81. int main (int argc, char *argv[])
  82. {
  83. printf ("%u\n", hash("abcdef"));
  84. install ("H", "127");
  85. printf ("%s\n", lookup("H")->defn);
  86.  
  87. undef ("H");
  88. if (lookup("H") != NULL)
  89. printf ("%s\n", lookup("H")->defn);
  90. }
Success #stdin #stdout 0s 2244KB
stdin
Standard input is empty
stdout
79
127
after loop