How can I know the allocated space has been freed successfully?

Does anyone know how we can check if allocated space is freed? The manual page says that "free () does not return a value."

+6
source share
4 answers

Three cases are possible:

free( NULL ); // does nothing, so always works free( malloc(42) ); // does something, always works free( 666 ); // undefined behaviour - returned value would be meaningless 

Thus, there is no case where testing free() has a point.

+12
source

There is no return value because there is no case of failure. free always succeeds. There is nothing to check.

Please note that this assumes that you are using it correctly. If you go to a free pointer that is not valid as an argument for free , for example, an uninitialized pointer, a pointer to an already freed object, or a pointer to an object not obtained with malloc , then your program has undefined behavior . This is not a reporting error; rather, it means anything can happen .

+10
source

The "wrong" free one will crash your application, so there is no need to make sure that it works :)

Example:

 #include <stdlib.h> int main(int argc, char **argv) { char *a = malloc(sizeof(*a) * 10); free(a); free(a); return 0; } 

$. / example * glibc ./ detected ; example: double freedom or corruption (fasttop): 0x08a3e008 ** ======= Backtrace: ========= / lib / libc.so.6 (+ 0x6c501) [0x17c501]

+1
source

If you want to check the internal workings of the heap allocator, I don’t think of a standard way to do this.

If you want to make sure that the memory has been reinitialized, I suggest you reset the memory before freeing it. I do not remember any guarantee of the free function for zero memory.

0
source

Source: https://habr.com/ru/post/887119/


All Articles