How to test if the free(); function worked correctly?

Asked

Viewed 139 times

1

I’m creating the abstract kind of 2D Matrix data, and one of the functions I’m doing in TAD is this:

int mat2D_free(TMat2D *mat)
{
    free(mat->data);
    free(mat);
}

That is, a function to destroy the matrix. My intention is that this function returns 0 if you have done the free(); successfully and -1, in the event of a failure.

What would be the appropriate test to know if the free(); in fact released the memory?

The pointer on which the free(); changes in some way?

2 answers

5


There’s no way. free() does not return value, therefore has no way to report success or failure.

In fact, you can only call free() with a valid pointer, allocated by malloc() and company; or NULL, case where it does nothing. Calling with an invalid pointer will cause heap corruption. Some systems can detect some cases of invalid or double pointer free(), ending the program immediately with a message, but even with this it is not possible to count. In general the implementation of free() is made to be extremely fast, and will manipulate the data pointed by the pointer assuming that are ok.

If you need to test the program to see if corruption is not occurring, you can try tools like Valgrind, but this is for debugging and checking, not something for production.

5

If you’re talking about checking if the function has played its role correctly then you don’t need to check anything, it always has, there’s no way it fails to be by a catastrophic situation on the machine, which makes your application and who knows something else become unviable, and the least of your problems is whether the free() worked. Or you may not have done what you expect because you called it wrong, for example passing something that is not a pointer or is a wrong pointer.

If you’re talking about determining whether you used the function correctly, there’s no way, you have to analyze the code deeply, or test all possibilities, which can be many, to find it, there’s no way the function itself.

And if you’re talking about releasing an allocation right, then your only chance beyond manual checking is to use some tool that tracks all allocations and shows when there is some abnormality. It’s not 100% safe but it helps a lot. One of them is Valgrind or Drmemory or Insure++.

If you try to use the value of the variable that was released you will have a undefined behavior because it no longer has a valid value. The variable that defined the pointer no longer has a valid value, so it can no longer access. The value remains the same. In C the programmer has to take care of this and not try to access what was valid just before, has no ease in language or library.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.