Segmentation fault (core dumped). Where's the mistake?



  • #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int main(int argc, char *argv[])
    {
        FILE *file;
        if(argv[1]==NULL) 
            printf("Synopsis: %s output_file\n",argv[0]);
        else
        {
            file = fopen(argv[0],"a+");
            if (file != NULL)
            {
                printf("Error: can't open file\n");
                return 1;
            }
            else
            {
                char *s=malloc(10*sizeof(*s));
                s="^F";
                for (char c = getc(stdin); c != 's'; c = getc(stdin))
                    {
                        fputc(c, file );
                    }
                free(s);
            }
            fclose(file);
        }
    }
    


  • There are several mistakes. First, you're checking if the parameter is set for the program.

    if(argv[1]==NULL) 
           ^^^
        printf("Synopsis: %s output_file\n",argv[0]);
    

    And then you try to open your own program file instead of a first-class file.

        file = fopen(argv[0],"a+");
                         ^^^
    

    If the file wasn't open, the function. fopen He'll return the zero index. Therefore, instead of the conditions in this if proposal

        if (file != NULL)
        {
            printf("Error: can't open file\n");
            return 1;
        }
    

    another condition

        if (file == NULL)
        {
            printf("Error: can't open file\n");
            return 1;
        }
    

    Then you've somehow given memory to a symbolic mass.

            char *s=malloc(10*sizeof(*s));
    

    I don't know who's being used anywhere. And now, the index redirects the address of the string literature.

            s="^F";
    

    As a result, you have a memory leak.

    And more so in this sentence

    free(s);
    

    You're trying to free the memory of a string literature that has a statistical length. Which could also lead to an uncertain programme behaviour.

    This cycle

           for (char c = getc(stdin); c != 's'; c = getc(stdin))
                {
                    fputc(c, file );
                }
    

    Nor is it correct the function getc may return the value EOFwhich you don't check the cycle.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2