-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;
}
3
  • How do you start your program after you compile it? Commented Feb 7, 2018 at 1:13
  • Try add breakpoint and debug. Commented Feb 7, 2018 at 1:15
  • char * s isn't pointing to anything right now. Commented Feb 7, 2018 at 1:27

2 Answers 2

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); 
Sign up to request clarification or add additional context in comments.

2 Comments

You had to leave one character for the null terminator, so 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.

4 Comments

Yeah I was still testing code when I uploaded it. Removed the NULL, but I still get told that "s may be uninitialized".
@AlanGhalan, s IS uninitialized. You need to initialize it.
@lurker for some reason the OP changed the code, if you check the history it was assigned NULL
@lurker As it appears it was, and the OP changed it. Read this comment.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.