0

Why does fgets segfault when I pass a char pointer as the first argument? For example:

char *p;
fgets(p, 10, stdin); // segmentation fault

What's with the char pointer p, when we just declare it as char *p (as in the above example)? thanks!

user438383
  • 5,716
  • 8
  • 28
  • 43
XMan
  • 29
  • 3
  • using the exact code as described p point to NULL and fgets() need memory to save the 10 characters – pascal sautot Oct 18 '21 at 09:15
  • 2
    You always have to answer the question "To what valid block of memory does my pointer point?", e.g. What address does my pointer hold as its value? A few links that provide basic discussions of pointers may help. [Difference between char *pp and (char*) p?](https://stackoverflow.com/a/60519053/3422102) and [Pointer to pointer of structs indexing out of bounds(?)...](https://stackoverflow.com/a/60639540/3422102) (ignore the titles, the answers discuss pointer basics) – David C. Rankin Oct 18 '21 at 09:16
  • 2
    @pascalsautot, it doesn't point to `NULL`, it's uninitialized. – frippe Oct 18 '21 at 09:22
  • 1
    I understand why new users post answers to this. But if you are a 10k+ rep and/or C gold badge user coming across a FAQ question like this, the correct action is to open the [C tag wiki](https://stackoverflow.com/tags/c/info), scroll down to "FAQ" to find a list of canonical duplicates, then close vote for the appropriate dupe. In this case one was found below FAQ -> Pointers. – Lundin Oct 18 '21 at 09:27
  • @frippe what difference do you make between uninitialiated (value is 0) and assigned by NULL (value is 0) both end up with the same problem a pointer that does not point on a memory space – pascal sautot Oct 19 '21 at 14:52
  • @pascalsautot Uninitialized does not imply 0, it means it contains a garbage value and could point _anywhere_ – frippe Oct 19 '21 at 15:01

4 Answers4

1

p contains a garbage value. You need to initialize it first.

char *p = (char*)malloc(10);
if (p == NULL) {
    // handle error
}
//use p

// Once you're done with p
free(p);

or

char p[10];  // Automatic storage
frippe
  • 1,329
  • 1
  • 8
  • 15
0

Pointer p must point to a buffer.

char buf[10];
char *p = buf;
fgets(p, 10, stdin);

should work now. Note that array expressions decays to pointers so the code could be simpified to:

char p[10];
fgets(p, 10, stdin);
tstanisl
  • 13,520
  • 2
  • 25
  • 40
0

fgets can and does take a valid pointer to a character buffer as the first argument. In your case, your char *p is not valid. It has not been initialised and probably points to a junk value.

You can either initialise it to a static string or a character array which contains some sensible value.

Noufal Ibrahim
  • 71,383
  • 13
  • 135
  • 169
0

Here p is just a pointer and it doesn't point to anything since it has not been initialized yet. You can initialize it via allocating memory to it.

char *p = (char*)malloc(10);