-2

I'm trying to make a basic C program to read from a file, but for some reason when I run it with make Test1 and then ./Test1 test1.txt I get "error: 's' may be used uninitialized in this function".

#include <stdio.h>
#include <stdlib.h>

int main (int argc, char** argv) {


    if (argc < 2) {
        printf("error\n");
        return 0;
    }

    FILE *fp = fopen(argv[1], "r");

    if (fp == NULL)  {
        printf ("error\n");
        return 0;
    }

    char * s;

    int r = fscanf(fp, "%s", s);

    while (r != EOF) {
        printf("%s\n", s);
        r = fscanf(fp, "%s", s);
    }

    return 0;
}
AlanGhalan
  • 388
  • 1
  • 3
  • 10

2 Answers2

1

The problem is with fscanf. It won't allocate any memory, you have to do this by yourself, e.g. by doing

char *s = malloc(100);  //array s is stored in the heap memory

or

char s[100];  //array s is stored in the stack

To make sure that fscanf won't read more than 100 characters (because that's how much memory we got) you have to write

int r = fscanf(fp, "%99s", s); 
0

It should be crashing as you are reading into s which is set to NULL, meaning there is no memory you have set aside to read into and it should crash your program, depending on OS depends on error

doing char s[1000] at least gives it some memory to read into.

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156