Hello All,
I am trying to write a C program that reads a text file and output unique words sorted alphabetically using /usr/bin/sort. All non-alphabetic characters serves as delimiters and are discarded. I am having a problem just parsing the text file into words, getting SEG FAULTS. dbx gives error: program terminated by signal SEGV (no mapping at the fault address). Error is generated by this line: strcat(word, (char *)tolower(c)); Any suggestions would be greatly appreciated. Code below:

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>
#include <sys/wait.h>
#include <ctype.h>
#include <string.h>


int main(int argc, char *argv[]){
	int i=0;
	pid_t child_pid;
	char *word, c;

	if(argc != 3){
		usage();
		exit(1);
	}
	FILE *input = fopen(argv[2], "r");
	if(input == NULL){
		printf("File '%s' does not exist or could not be accessed.\n", argv[2]);
		exit(1);
	}


	word = (char *)malloc(100);
	while((c = fgetc(input)) != EOF){
		while(!isalpha(c) && !isspace(c))
			c = fgetc(input);
		if(isalpha(c)){
			strcat(word, (char *)tolower(c));
			//word += c;
		}
		else{
			puts(word);
			free(word);
		}
		
	}
	fclose(input);

	
	
	return 0;
}


void usage(){
	printf("usage: uniqify n filename\nn is the number of sorters to use and filename is the textfile to sort\n");
}

Well assuming all your strings are going to fit into 100 characters, the first thing you need to do before using strcat is to make sure the string is empty.
malloc returns memory which contains garbage, so begin with
word[0] = '\0';

Then you try to append a single character with strcat, by casting it (which shuts the compiler up), but doesn't actually fix the problem so it will work.

You also free word after the first word is found, but carry on using deallocated memory until the end of the file.

Yes, it's well broken in other words.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.