0

I'm curious about one thing, the following code works perfectly.

#include <stdio.h>
int main()
{
  FILE * fp = fopen("test.txt", "r");
  char line[100];

  while( fgets(line, sizeof(line), fp) != NULL )
    fputs(line, stdout);
  fclose(fp);
  return 0;
}

But why it is not possible to use instead:

char *line;

Without causing fgets to crash?

cap7
  • 482
  • 5
  • 24

3 Answers3

3

It is possible. Just point it to some valid memory.

char line[100];
char* linep = line ;
while( fgets(linep, sizeof(line), fp) != NULL )...

If you don't assing line to linep, then linep points to random memory, and you cannot use that.

this
  • 5,229
  • 1
  • 22
  • 51
3

fgets crashes because it is writing the result into unallocated memory.

Without any further memory allocation, char *line points to "nothing". It points to something, but not to any valid memory location -- null if your compiler sets uninitialized values to 0, or any random memory location anywhere on or not on your system.

Even if fgets does not crash, you cannot predict what it does as writing into unallocated memory results in undefined behavior (What is undefined behavior?).

Community
  • 1
  • 1
Jongware
  • 22,200
  • 8
  • 54
  • 100
1

char *line and char line[100] don't mean the same. The first is a pointer to a char, we don't know if it will be a single char or an array of chars it is pointing to. The second on the other hand is an array.

fgets needs a valid location to write to. In this case, char *line doesn't have any valid location to point at, whereas char line[100] is a valid char array location

Suvarna Pattayil
  • 5,136
  • 5
  • 32
  • 59