-3

something strange happens in my code. I'm using fgets to get each line of a file and then I use strtok to parse it. using Ubuntu, if I compile using gcc -o name name.c, it gives me segmentation fault. If I compile using -fsanitize=address, the code runs perfectly without any segv. What could be the problem?

the code is:

char* input;
fgets(input, 1000, stdin);
tok=strtok(input, pars);

but it looks like it stops at fgets.

Kiran Maniya
  • 8,453
  • 9
  • 58
  • 81
Pit2752
  • 1
  • 1
  • 2
  • 1
    The address sanitizer is able to detect only some kinds of undefined behavior. Enabling the ASAN may also modify the produced code in such a way that the UB does not trigger a segmentation fault anymore. Thus a [repro] to answer more specifically would be necessary. – walnut Sep 07 '19 at 18:32
  • okay, i use char* input; fgets(input, 1000, stdin); tok=strtok(input, pars); but it looks like it stops at the fgets – Pit2752 Sep 07 '19 at 18:38
  • 1
    That is not a [repro]. Please read the link again and make sure your example code is *complete* and *reproducible*. – walnut Sep 07 '19 at 18:40
  • Welcome to Stack Overflow. Please read the [**About**](http://stackoverflow.com/tour) page soon and also visit the links describing [**How to Ask a Question**](http://stackoverflow.com/questions/how-to-ask) and [**How to create a Minimal, Complete, and Verifiable example**](http://stackoverflow.com/help/mcve). Providing the necessary details, including your code, compiler warnings and associated errors, if any, will allow everyone here to help you with your question. – David C. Rankin Sep 08 '19 at 07:58

2 Answers2

1

What could be the problem?

Your line

char* input;

just declares a pointer to char without assigning an address to it. Where do you think will it point at?

Then you want to

fgets(input, 1000, stdin);

for at most 999 characters, but you never provide the space for them.

If you change the first line to

char input[1000];

it will work without segmentation error.

the busybee
  • 10,755
  • 3
  • 13
  • 30
0

in your code it is obvious that you want to get a string by using fgets, what the compiler thinks is that the pointer will be used to point at an address, but instead you use it to point at a string causing the segv

the proper approach is this

char *input = malloc(<any size you want>);
fgets(input, <the size you want>, <the stream you want to get from>);

and this approach should solve your problem

  • This has nothing to do with what the pointer points to, but instead is because he didn't allocate memory for the pointer first. Also, to point to a string is to point to an address, so your first sentence doesn't really make sense. – palapapa Jul 15 '23 at 18:16