Search code examples
crealloc

How can I make sure that a caller passes a malloc'd pointer?


I have a function which reallocs a pointer given as an argument to a new size. Now, the problem is that - according to the man page - realloc needs a pointer which has been returned by malloc or calloc before.

How can I make sure that the caller passes a pointer that meets those requirements? There seem to be no build-in C mechanics (like type qualifiers or something) to do so.

Now, before I restructure my API (as I consider the function as it is now not to be robust enough) - can you please verify that I haven't missed something?

Thanks in advance.

Edit: One solution would obviously be to malloc in the function. The problem with that is that the caller does not "see" the allocation. Thus I would need to explictly say in the docs that he has to free the pointer. That's even worse than to expect them to provide a malloc'd pointer (which would imply that the caller has to free it).

What I really want is something that blocks abuse at compile time. That, and a pony. ;-)


Solution

  • How can I make sure that the caller passes a pointer that meets those requirements?

    Documentation.

    Define the API.

    If the person writing the caller refuses to follow the API, things crash. They refused to play by your rules and things crashed. What did they expect?