The statement:
char *input1, *input2;
allocates memory for two pointers to char
. Note that this only allocated memory for that pointers — which are uninitialised and aren't pointing to anything meaningful — not what they're pointing to.
The call to scanf()
then tries to write to memory out of bounds, and results in undefined behaviour.
You could instead, declare character arrays of fixed size with automatic storage duration:
char input1[SIZE];
This will allocate memory for the array, and the call to scanf()
will be valid.
Alternatively, you could allocate memory dynamically for the pointers with one of the memory allocation functions:
char *input1 = malloc (size);
This declares a pointer to char
whose contents are indeterminate, but are immediately overwritten with a pointer to a chunk of memory of size size
. Note that the call to malloc()
may have failed. It returns NULL
as an error code, so check for it.
But scanf()
should not be used as a user-input interface. It does not guard against buffer overflows, and will leave a newline in the input buffer (which leads to more problems down the road).
Consider using fgets
instead. It will null-terminate the buffer and read at most size - 1
characters.
The calls to scanf()
can be replaced with:
fgets (buf, sizeof buf, stdin);
You can then parse the string with sscanf
, strtol
, et cetera.
Note that fgets()
will retain the trailing newline if there was space. You could use this one-liner to remove it:
buf [strcspn (buf, "\n\r") = '\0`;
This takes care of the return carriage as well, if any.
Or if you wish to continue using scanf()
(which I advise against), use a field width to limit input and check scanf()
's return value:
scanf ("%1023s", input1); /* Am using 1023 as a place holder */
That being said, if you wish to read a line of variable length, you need to allocate memory dynamically with malloc()
, and then resize it with realloc()
as necessary.
On POSIX-compliant systems, you could use getline()
to read strings of arbitrary length, but note that it's vulnerable to a DOS attack.