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. ;-)
malloc returns a void pointer to the allocated space, or NULL if there is insufficient memory available. To return a pointer to a type other than void , use a type cast on the return value.
C library function - free() The C library function void free(void *ptr) deallocates the memory previously allocated by a call to calloc, malloc, or realloc.
In C, the library function malloc is used to allocate a block of memory on the heap. The program accesses this block of memory via a pointer that malloc returns. When the memory is no longer needed, the pointer is passed to free which deallocates the memory so that it can be used for other purposes.
The function free() is used to deallocate the allocated memory by malloc(). It does not change the value of the pointer which means it still points to the same memory location. Here is the syntax of free() in C language, void free(void *pointer_name);
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?
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