benny
benny

Reputation: 11

How to check if an address in C is valid or allocated?

I am implementing my own free using a static array of 1000 bytes for a problem.Two problems that can occur is if they passed in a parameter that isn't a pointer (char a; free((&a));) since free takes in a void pointer(free(void*p)).

Also, when the user doesn't malloc being used char * a; free(a);. How would you suggest I check for these edge cases. I am aware that pointers have no information other than what they point too so I'm stumped on how I can differentiate whether something is a int being pointed to or just a regular int.

Upvotes: 0

Views: 1143

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 222272

The way to do this is:

  • In your allocation routine, remember the addresses you give out.

  • In your free routine, check the address being freed. If it is not one you gave out, report an error. If it is, remove it from your list of outstanding addresses.

A lighter weight solution is simply to check every address passed to your free routine to see if it is inside your array. This will catch attempts to free something that is outside your array, but it will not catch calls that free an address previously freed or a slightly modified address that is still in your array.

Note that comparing arbitrary pointers with < or > is not actually defined by C. (It is only defined if it is already known they point within the same array. However, common C implementations permit this, and it is tolerable for a learning exercise.)

Upvotes: 2

Related Questions