0

I have to pass a maximum of 100 charcters from a file to a char pointer. Why do I get segmentation fault error?

#include <stdio.h>

void read_file(FILE *in, char *s);

int main(void){
    FILE *in;
    char *s;
    in = fopen("input", "r");
    read_file(in,s);
    printf("%s", s);
    return 0;
}

void read_file(FILE *in, char *s){
    int c, count = 0;
    while((c=getc(in))!=EOF && count < 100){
        s[count] = c;
        count++;
    }
}

This error has been bothering me for a while now and I don't understand why.

1 Answers1

1

s is an uninitialized pointer. It points nowhere.

You want this:

char s[100];

Instead of:

char *s;

I suggest you read the chapter dealing with pointers in your C text book.

You also need to check if fopen was successful:

in = fopen("input", "r");
if (in == NULL)
{
  printf("Can't open file\n");
  exit(1);
}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115