Reputation: 31
I have a question, about C-function free(). What will happen, if first I'll allocate memory for char-string, then past '\0' to any position of the string and set the new pointer to the next after '\0' position? If after I will try use free on the initial pointer, is there a memory leak? Or compilator knows termination position and free all of the allocated memory? Manuals say "Frees the pointer, allocated by malloc", but I still have no full understanding of this process.
There's an example:
#include "stdlib.h"
int main()
{
int i = 0;
char* test = (char*)malloc(sizeof(char) * 100);
char s = 'a';
for (int i = 0; i < 10; i++)
test[i] = s;
test[10] = '\0';
char* v = (test + 6);
test[4] = 0;
free(test);
return 0;
}
Valgrind says:
Address 0x522d048 is 8 bytes inside a block of size 100 free'd
Upvotes: 0
Views: 423
Reputation: 2395
Memory allocation with malloc
allocates the number of bytes requested and returns a pointer to the beginning of the allocated range.
Function free()
deallocates the range only when you pass the pointer returned by malloc
. Any other pointer passed to free
invokes "undefined behavior".
Neither function knows or cares what information you place in the range of allocated bytes.
Moreover, freeing a NULL pointer does nothing since according to the standard value of NULL is internally checked.
Upvotes: 1
Reputation: 222427
malloc
reserves memory for your use and returns a pointer to that memory. Internally, malloc
remembers information about that memory. In particular, it remembers how much it reserved.
When that same pointer is passed to free
, free
terminates the reservation.
Once that reservation is ended, you should not use any of that memory. In your example, when you call free(test)
, all of the memory that was reserved by malloc(sizeof(char) * 100)
is released. The fact that you put a null character in part of it and have data later after is irrelevant. The fact that you still have a pointer v
that points to somewhere in the memory is irrelevant. free
releases all of the memory that was allocated, regardless of contents.
(This does not mean that attempting to use the memory will not work. After you call free
, the memory is no longer reserved for you to use. But it is possible that nothing will act to prevent you from using it—no trap is guaranteed to occur if you try. But it is also possible that a trap might occur or that other software in your program might use that memory, so your use of it could interfere.)
Upvotes: 1