when i compile this,. it is showing segmentation fault.. can anyone help me,..

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • khaja51
    New Member
    • Jul 2010
    • 1

    #1

    when i compile this,. it is showing segmentation fault.. can anyone help me,..

    #include<stdio. h>
    #include<conio. h>
    #include<string .h>
    struct intermediate
    {
    int addr;
    char label[10];
    char mnem[10];
    char op[10];
    }res;
    struct symbol
    {
    char symbol[10];
    int addr;
    }sy;
    int main()
    {
    FILE *s1,*p1;

    s1=fopen("inter .txt","r+");
    p1=fopen("symbo l.txt","w");
    while(!feof(s1) )
    {
    fscanf(s1,"%d %s %s %s",&res.addr,r es.label,res.mn em,res.op);
    if(strcmp(res.l abel,"NULL")!=0 )
    {
    strcpy(sy.symbo l,res.label);
    sy.addr=res.add r;
    fprintf(p1,"%s\ t%d\n",sy.symbo l,sy.addr);
    }
    }
    _fcloseall();

    printf("symbol table created");
    getch();
    return;
    }
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Did you check s1 and p1 to be sure the files opened?

    Comment

    • Oralloy
      Recognized Expert Contributor
      • Jun 2010
      • 988

      #3
      You should check for EOF or Error after the fscanf, as well.

      (Actually, it's best to check for errors after all system calls, including your opens, but for disposable software you're usually fine.)

      Likewise, the compare to the string "NULL" may not be what you want. Is that supposed to be your error check on the fscanf? If so, you'd better go back and read the documentation on fscanf once again.

      fscanf documentation.

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        Segmentation fault is typically a run-time error, not a compile-time error. Are you sure about when this error occurs?

        Please use CODE tags around your source code. That makes it easier to read the code, and provides line numbers that we can refer to.

        You should follow Oralloy's advice and verify that each of your fopens succeed. You should also verify that fscanf and fprintf succeed. I'm not familiar with _fcloseall, can it fail?

        On the fscanf line, you read in three strings, each into a 10-char array. What if the input file contains strings longer than that? Writing past the end of an array is undefined behavior. You want to protect your program from undefined behavior.

        On the fscanf line, what happens if the input line doesn't match the format string? In that case some (or all) of the variables don't change. If that happens the first time through the loop then the variables contain total garbage, otherwise they contain values from the prevous iteration.

        On the strcmp and strcpy lines, what happens if res.label contains garbage (see above)? Most notably, what if the array doesn't contain any nulls?

        Comment

        Working...