-1

The following is a program I wrote in gdb in the following link :

https://www.onlinegdb.com/online_c_compiler

#include <stdio.h>
    #include <string.h>


int main()
{
    char abc[] = "love";
    char *hon[100];
    FILE *d, *e;
    int n;
    char c;
    d = fopen("demo.txt", "r");
    /*e = fopen("demo.txt", "w");*/
    /*n = fputs(abc,e);*/
    printf( "jhjhj \n");
    while ((n = getc(d)) != EOF)
       {
        printf( "kjkjkkj \n");
        if (n == 'a')
        {
            /*e = d;*/

            /*n = putc('k',e);*/
        }
    }

    printf("%s", abc);

    printf("abcdefgh %d hjhjh %d", 5, 6);
    putchar(abc[1]);





}

But I am getting segmentation fault while trying to execute this code .

I went through the following question :

What is a segmentation fault?

Segmentation fault is an error that comes when we try to access a memory location which is unassigned or the program doesn't have any access to or when one process tries to access a location of memory which another process is already accessing.

So , I thought that opening the same file in read and write mode might be resulting in this although I could not explain how that might be happening .

As such I commented the part which tries to access the file in "write" mode . Even after that I got the same segmentation fault error .

So , I put some messages before different parts of the code . As it turns out , I could not get the message just before the fopen .

I could not understand how might be violating access of memory rules here even after commenting out the part which opened the file in write mode .

Looking forward for insights and helps .

Is it because of the reason that file does not exists . But in that case , on encountering EOF it should exit out of the while loop , but why an error ?

  • you haven't even checked if the file was opened. – Eugene Sh. May 01 '18 at 17:18
  • Install Linux on your own laptop. Then compile with all warnings & debug info (`gcc -Wall -Wextra -g` with [GCC](http://gcc.gnu.org/). Improve the code to get no warnings. Then [use the `gdb` debugger](https://sourceware.org/gdb/current/onlinedocs/gdb/) – Basile Starynkevitch May 01 '18 at 17:19
  • 1
    @BasileStarynkevitch I can't tell if it is satire, but you don't need Linux to run gdb :/. Also in addition to those fine flags I would also suggest `-Wall -Wextra -pedantic -Werror` – Srini May 01 '18 at 17:21

1 Answers1

4

You did not check that your file opened successfully

d = fopen("demo.txt", "r");

If it fails d will be NULL and attempting to read from the non-existent file causes a segfault

n = getc(d) // segfault if d was not actually opened
Increasingly Idiotic
  • 5,700
  • 5
  • 35
  • 73