Code fails with Segmentation Fault



Hello,

I am trying to learn C, especially pointers. The following code
attempts to count the appearences of each word in a text file, but
fails invariably with Segmentation Fault. Please help me out, I've
already tried all my ideas. Also, please do comment on my coding style
or other aspects. Thank you.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define INITLEN 5
#define DELTA 5

int main(int argc, char **argv)
{
char **words, *word, *string;
int *apps, max, found, i, n;
FILE *input;

if (argc != 2) {
printf("Usage: %s <file>\n", argv[0]);
return 0;
}

max = INITLEN;
n = 0;
words = (char **) calloc(max, sizeof (char *));
apps = (int *) calloc(max, sizeof (int));
input = fopen(argv[1], "r");

while (fgets(string, 1000, input)) {
word = strtok(string, " ");
while (word) {
found = 0;
for (i=0; i<n; i++)
if (!strcmp(words[i], word)) {
found = 1;
apps[i]++;
break;
}
if (!found) {
words[n] = strdup(word);
apps[n] = (int) malloc(sizeof(int));
apps[n] = 1;
n++;
if (n == max) {
max += DELTA;
words = (char **) realloc(words, max);
apps = (int *) realloc(apps, max);
}
}
word = strtok(NULL, " ");
}
}

for (i=0; i<n; i++)
printf("Word '%s' appears %d time(s).\n", words[i], apps[i]);

return 0;
}

.



Relevant Pages

  • Re: dynticks + iptables almost stops the boot process [was: Re: 2.6.20-rc6-mm3]
    ... int64_t delta; ... -static int tick_broadcast_reprogram ... goto again; ... extern void clockevents_notify ...
    (Linux-Kernel)
  • Re: Encryption ??
    ... the sizeof test isn't an exact multiple of 8 and you don't see the problem. ... unsigned long delta = 0x9E3779B9; ... static void decode(unsigned long *enc, unsigned long *key, unsigned long *dec) ...
    (comp.lang.clipper)
  • Re: Cleaning up FILE in stdio..
    ... What would work, although it would be extra pain, would be to extend ... I guess we could add a _nfile that is an int, and try to keep _file up ... Newer apps would just always use _nfile. ...
    (freebsd-arch)
  • Re: Encryption ??
    ... unsigned long sum = 0; ... unsigned long delta = 0x9E3779B9; ... char enc; ...
    (comp.lang.clipper)
  • Re: Is the delta function absolutely integrable?
    ... The question I have is, what about int |delta| dt, i.e., the ... sequences that tend to delta that are absolutely integrable, ... to the delta function as it grows skinnier and taller; ... In the distributional sense, yes, the delta ...
    (sci.math)