Reputation: 205
I have a program written in C which should count the number of times the word "the" appears in text files that are given as arguments.But the program keeps giving a segmentation fault error and I have no more ideas on how to solve this.Any help would be appreciated.Thank you!
Here is the code:
#include <stdio.h>
#include <string.h>
void main(int argc, char *argv[])
{
int h,i;
FILE *fp;
char* mess;
for(i=1; i < argc; i++)
{
h=0;
fp=fopen(argv[i],"r");
while (!feof(fp))
{
fscanf(fp,"%s",mess);
if (strcmp(mess,"the")==0)
h++;
}
printf("The file %s contains the word \"the\" %d times.",argv[i],h);
h=0;
fclose(fp);
}
}
Upvotes: 0
Views: 2685
Reputation: 41749
char* mess;
[...]
fscanf(fp,"%s",mess);
mess is uninitialised. You need to allocate some space for the word you are reading in
s Matches a sequence of non-white-space characters; the next pointer must be a pointer to char, and the array must be large enough to accept all the sequence and the terminating NUL character. The input string stops at white space or at the maximum field width, whichever occurs first.
so you also want to use the field width to limit what you read to the size of your buffer. This requires a bit of careful handling since the bit after your buffer size just might be "the" (e.g. "breathe", if you read 4 character words, would give you "brea" and "the" and a false positive)
Upvotes: 5
Reputation: 13672
allocate memory for mess using either mess=malloc(sizeof(char)*SOME_NUMBER)
or simply declaring mess as array of characters i.e char mess[1024];
Upvotes: 0
Reputation: 381
As far as I can read from the code, you have not initialized the mess
pointer before you used it to be populated by the fscanf:
fscanf(fp,"%s",mess);
Upvotes: 0
Reputation: 13025
while (!feof(fp))
{
fscanf(fp,"%s",mess);
if (strcmp(mess,"the")==0)
h++;
}
You're reading a string from a file, putting it into mess
, which is a plain pointer to a char. You need character array:
char mess[1000];
Upvotes: 0
Reputation: 21896
You need to allocate memory for the buffer mess
being given to sscanf
:
char mess[256];
Currently, mess
is uninitialized (null). sscanf
trips over trying to write to it.
Upvotes: 0
Reputation: 76745
The char* mess
is an unitialized pointer. In other words : it is a variable whose value is a random address in memory. In your call to fscanf
an attempt will be made to write something at this address and your program will crash.
Either make mess
an array of fixed size or make it point to a valid memory block which has been dynamically allocated using malloc
(which is probably useless here). In both cases, you'll probably want to make sure that you cannot read more than size
character or you'll end up with a whole new segmentation fault.
Upvotes: 1