I wrote the following toy program and observed that the second variable test2 will take the memory address released by the first variable test1. And even if I free(test1), test2 will retain test1's fields values. I wonder how to clean up the data left behind by free() in C:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct test_str
{
char name[128];
int Id;
} test_str;
typedef test_str* mytest;
int main()
{
mytest test1 = malloc(sizeof(test_str));
printf("test1 pointer address is %p \n", test1);
strcpy(test1->name, "hello world");
test1->Id = 10;
free(test1);
// test1->name = NULL; /* this does not work */
// test1->Id = 0; /* without resetting Id = 0, test2->Id will show 10 */
test1 = NULL;
mytest test2 = malloc(sizeof(test_str));
printf("test2 pointer address is %p, name field is %s, Id = %d \n", test2, test2->name, test2->Id);
return 0;
}
this is the output:
test1 pointer address is 0x2401010
test2 pointer address is 0x2401010, name field is hello world, Id = 10
“free” method in C is used to dynamically de-allocate the memory. The memory allocated using functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it.
When you no longer need a block that you got with malloc , use the function free to make the block available to be allocated again. The prototype for this function is in stdlib. h .
If your data is that sensitive, use platform calls to pin the memory and use a non-elidable call to some memset
-variant to clear before free.
When you give memory back to the runtime, it is free to use it for the next fitting request. Whether and when it does so, or if it gives the memory back to a possible OS, is not mandated by the standard.
Aside: void free(void*) {}
is a valid implementation of free
.
As the comments have mentioned, just use memset
before free
.
memset(test1, 0, sizeof(*test1));
free(test1);
There is hardly any good reason on earth why one would want to do this...
Nevertheless, adding test1->name[0]=0
before free(test1)
should do the job.
If you want to remove "all trace" of the previous text, then you can even do:
for (int i=0; test1->name[i]!=0; i++)
test1->name[i]=0;
free() does not clear memory in sense of zeroing it – it just makes it available for reuse – and that is exactly what happened here. If your intent is to have alocated memory initialized, consider using calloc().
You can use memset(test1, 0, sizeof(test_str))
just before freeing, this will simply fills the allocated memory area with 0.
malloc algorithm actually works by keeping meta data for each memory block it creates. So if you allocate / free / re-allocate the same size just after, you will probably use the exact same memory block, which explains why the new address is the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With