Don't use gets
. It is dangerous and obsolete. Use fgets instead. Replace gets(p->n)
with fgets(p->n, sizeof(p->n), stdin);
and so on.
Don't name your function read
(since that is the name of a POSIX standard function). Replace it by another name, e.g. myread
.
You probably want to do:
X *p1=malloc(sizeof(X));
in your main. Then, you need to check that malloc
succeeded:
if (!p1) { perror("malloc p1"); exit(EXIT_FAILURE); }
Beware that malloc
gives (on success) some uninitialized memory zone. You may want to clear it using memset(p1, 0, sizeof(p1))
, or you could use p1 = calloc(1, sizeof(X))
instead.
At last you can pass it to your myread
:
myread(p1);
Don't forget to call free(p1)
(e.g. near the end of your main
) to avoid a memory leak.
Learn to use valgrind, it catches many memory related bugs.
Of course you need to carefully read the documentation of every standard function that you use. For example, fgets(3) documents that you need to #include <stdio.h>
, and that call to fgets
can fail (and your code needs to check that, see also errno(3) & perror(3)...). Likewise, malloc(3) wants #include <stdlib.h>
and should be checked. And scanf(3) can fail too, and needs to be checked.
You should compile with all warnings and debug info (gcc -Wall -Wextra -g
with GCC), improve your code to get no warnings, and you should use the gdb
debugger; you may want to use GCC sanitizers (e.g. instrumentation options like -fsanitize=address
, -fsanitize=undefined
and others),
Beware of undefined behavior (UB). It is really scary.
PS. I hope that you are using Linux with gcc
, since it is a very developer friendly system. If not, adapt my answer to your operating system and compiler and debugging tools.