There are multiple issues with your program:
- Since you're using
malloc()
and free()
, you should do #include <stdlib.h>
before calling any of those functions.
- There's no need to cast the return value from
malloc()
: it returns a void *
, which can be assigned to any other pointer type safely (except function pointers). So, you can do: p = malloc(10);
- Once you free a pointer allocated by
malloc()
or realloc()
, using the pointer value in any way is bad: in particular, you cannot call free()
on it again.
int main()
is better written as int main(void)
.
- Since
main()
returns int
, you should return a value from it. Traditionally, 0 means success.
Of course, the main (no pun intended) problem with your program is freeing it many times, but other issues mentioned above are important too. Once you've free()
'd a pointer successfully, calling free()
on it is undefined behavior: the program can do anything, including (unfortunately), seeming to not do anything bad. I say "unfortunately" because it might give you a sense of security that it's okay to free()
a pointer more than once.