feof or fscanf error

841 Views Asked by At

I am doing a program, I use Dev C++. While running my program terminates. On debugging it says 'segmentation fault'. I don't know if it going to infinity loop. I dont know if the problem is with the while(!feof(program)) or the fscanf(...) in the code.

Can anyone help in resolving this? See my program below:

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
    fpos_t curDesStart,curDesEnd;
    fpos_t curDesLocBackup,curDes;
    char *label,*opc,*operands;
    char *curMacroName;
    FILE *namTab,*desTab,*temp,*program;
    namTab=fopen("namTab.txt","rw");
    desTab=fopen("desTab.txt","rw");
    temp=fopen("temp.txt","w");
    program=fopen("program.txt","r");
    while(!feof(program))
    {
        fscanf(program,"%[^\n]%[^\n]%[^\n]",label,opc,operands);

        if(!strcmp(label,"MACRO"))
        {
            fprintf(desTab,"%s%s%s\n",label,opc,operands);
            fgetpos(desTab,&curDesStart);
            strcpy(curMacroName,label);
            while(!strcmp(opc,"MEND"))
            {
                fscanf(program,"%s%s%s",label,opc,operands);
            }
            fprintf(desTab,"%s%s%s\n",label,opc,operands);
            fgetpos(desTab,&curDesEnd);

            fprintf(namTab,"%s%ld%ld\n",curMacroName,curDesStart,curDesEnd);

        }

        else
        {
            while(!feof(namTab))
            {
                fgetpos(desTab,&curDesLocBackup);
                fscanf(namTab,"%s%ld%ld",curMacroName,curDesStart,curDesEnd);
                if(!strcmp(curMacroName,label))
                {
                    fsetpos(desTab,&curDesStart);
                    fscanf(desTab,"%s%s%s\n",label,opc,operands);
                    fprintf(temp,".%s%s%s\n",label,opc,operands);

                    do{
                        fprintf(temp,"%s%s%s\n",label,opc,operands);
                        fgetpos(desTab,&curDes);
                    }while(curDes<=curDesEnd);

                    fsetpos(desTab,&curDesLocBackup);
                    fsetpos(namTab,0);
                }
                else
                {
                    fprintf(temp,"%s%s%s\n",label,opc,operands);
                }
            }

        }
    }
    fclose(program);
    fclose(namTab);
    fclose(desTab);
    fclose(temp);
    getch();
    return 0;
}
2

There are 2 best solutions below

0
On

There are several problems with this code:

0
On

You have not neither allocated storage for any of your char *s to point to, nor have you even initialized them to point to something else. As a result, you are essentially passing random numbers into fscanf, which leads to Undefined Behavior, of which a program crash is one possible incarnation.