Code fails with Segmentation Fault
- From: "Vlad Dogaru" <ddvlad@xxxxxxxxx>
- Date: 28 Nov 2006 09:07:14 -0800
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;
}
.
- Follow-Ups:
- Re: Code fails with Segmentation Fault
- From: Bill Medland
- Re: Code fails with Segmentation Fault
- From: Eric Sosman
- Re: Code fails with Segmentation Fault
- From: dcorbit
- Re: Code fails with Segmentation Fault
- Prev by Date: Re: Please Help ----------Free Downloadable Ebooks for C & C++ Language needed
- Next by Date: Re: I am studying c myself .Which books I should read?
- Previous by thread: a scanf() question
- Next by thread: Re: Code fails with Segmentation Fault
- Index(es):
Relevant Pages
|