As the man page for free
will tell you, any argument except a pointer returned from malloc
has undefined behaviour:
The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed
Regarding how free
knows the size of the block: a typical memory allocator implementation has a header for each block (containing size, freelist pointers, etc.) and free
knows the size of this header and the offset from the pointer returned by malloc
.
This also answers your first question: malloc
allocates such a block and returns a pointer to the start of the actual object.
1
solved How many bytes will be deallocated with free() after changing the pointer?