-3

I had been trying to create a function that searches for a specific word at a file...My program compiles,but its execution is terminated at some point... The function is:

void search(struct word *w,FILE *f)
{
    char *c,*c2;
    int i,j,n,k,l;
    c=(char*)malloc(120*sizeof(char));
    c2=(char*)malloc(20*sizeof(char));
    while(f!=NULL)
    {                   
        j=0;
        i=1;
        fscanf (f,"%[^\n]%*c",c);
        printf("%s",c);
        n=strlen(c);
        k=0;
        l=j;
        while(l<=n && *(c+j)!=' ')
        {    
            *(c2+k)=*(c+j);
            printf("1");
            printf("%s",*(c2+k));
            printf("2");
            k=k+1;
            l=l+1;
        }      
        if(w->name==c2)
        {
            insert(i,j+1,name,&w);
        }
        else
        {
            if(l<n)
                j=l+1;
            k=0;
            c2=(char*)malloc(20*sizeof(char));
            l=j;
        }
        i=i+1;
        j=0;
    }
}

The main function is:

   int main()
   {
       FILE *f;
       struct word *s;
       s=(struct word*)malloc(sizeof(struct word));

       struct word *hashtable[100];
       s->name=(char*)malloc(20*sizeof(char));
       scanf("%s",s->name);
       f=fopen("fileA.txt","rt");
       char *name="fileA.txt";
       search(s,f);
       printresults();
       system("pause");
       return(0);
   }

And the structs are:

struct position
{
   char *filename;
   int line;
   int place;
   struct position *next;
};

struct word
{
    char *name;
    struct word *right;
    struct word *left;
    struct position *result;
};

The program terminates between the printf("1") and printf("2").

What is wrong with my code?

dragosht
  • 3,237
  • 2
  • 23
  • 32
user3697730
  • 251
  • 1
  • 3
  • 13
  • 2
    Two things: [Don't cast the result of `malloc`](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc), and `sizeof(char)` is specified to *always* be 1. – Some programmer dude Jul 13 '14 at 11:37
  • 1
    "..its execusion is terminated at some point.." That's perfectly normal, for many end user programs anyway. – Jongware Jul 13 '14 at 11:41
  • Well, @JoachimPileborg you are right...!I thought that it would be the same with %s...!Thanks! – user3697730 Jul 13 '14 at 11:50
  • However,there is still a problem...After reading the first line of my file,the program terminates again...What's the problem this time? – user3697730 Jul 13 '14 at 11:56

1 Answers1

2

If the crash happens somewhere between you print "1" and "2" it should be very easy to find, as there's only one statement there.

And it is easy to find:

printf("%s",*(c2+k));

The printf function is asked to print a string, but you pass a single character by using the dereference operator. That leads to undefined behavior when printf treats that single character as a pointer to a string.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621