Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

realloc

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. ;-)

like image 679
RWS Avatar asked Jul 23 '10 14:07

RWS


People also ask

Does malloc return a pointer?

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.

How to free memory of pointer in C?

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.

How work malloc?

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.

How free() works in C?

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);


1 Answers

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?

like image 53
S.Lott Avatar answered Sep 20 '22 03:09

S.Lott