Hi,
Why I am not getting any run time error while accessing a freed memory
in following code.
Because your program's behavior is undefined. This means
that from the language perspective, it could do absolutely
anything at all, from 'seems to work', to a crash, anything
in between, or something else.
This is printing h in std output.
It also might have caused the monitor to fall of the desk.
Moral: Don't Do That.
#include <stdlib.h> /* declares 'malloc()' and 'free()' */
#include said:
int main(void)
{
char* buffer = (char*)malloc(6);
You forgot to check if 'malloc()' succeeded. If it
failed, it returns NULL, in which case the call
to 'strcpy()' would give undefined behavior, because
it would try to dereference a null pointer.
Also, your casting of 'malloc()'s return value hides a
serious error: There's no prototype for 'malloc()' in
scope, which will cause a C89 compiler to assume it
returns type 'int'. So your cast tries to convert
a pointer type to an integer type. The language
does not define such a conversion. This conversion
is implementation-defined, but in any case it will
very likely corrupt the returned pointer value, in
which case you have more undefined behavior.
strcpy(buffer,"hello");
free(buffer);
printf("buffer=%c\n", *buffer);
return 0;
It's been a while since I've seen so many errors in such
a small piece of code.
-Mike