You should be passing str1
, not &str1
, to scanf()
.
scanf()
expects a char *
for the "%s"
format; you pass the address of a char *
. This does not lead to happiness.
Since BUF_SIZE is so small — just 10, you say — you need to use:
if (scanf("%9s", str1) != 1)
…process error or EOF…
This will protect you against buffer overflow. You should specify the size every time you use %s
(unless you use the POSIX modifier %ms
to scanf()
, but then the rules all change). If you don't, scanf()
can write outside the bounds of your string variable without knowing.
You should also check that malloc()
succeeds. Always. Every time.
Note that compiling with GCC and -Wall
(or -Wformat
) will point out the error of your ways. If you're using GCC, you should always compile with -Wall
(and preferably -Wextra
too — I use more options than that) to get better error reporting.
For a file with your code in it, GCC said:
warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char **’ [-Wformat=]
or 'error' when compiling with -Werror
too, which I regard as good practice.
I note in passing that GDB is telling me that you probably entered abc
as the string on a little-endian (e.g. Intel) machine. The value 0x636261
corresponds to that. You overwrote the pointer returned by malloc()
because you passed the address of str1
instead of the value in str1
— leaving memory corruption.