i was running a small c program:
#include
int main()
{
char *p;
p = (char *)malloc(10);
free(p);
free(p);
free(p);
printf(\"\\npointer is freed!!\
There are multiple issues with your program:
malloc()
and free()
, you should do #include <stdlib.h>
before calling any of those functions.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);
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)
.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.