Although it is possible that some libraries will allow you to determine the size of the allocated buffer, this will not be a standard C function, and you should look at your library for your own documents for this.
However, if there are many places where you need to know the size of the allocated memory, the cleanest way to do this is to save the size next to the pointer. I.e:
struct pointer { size_t size; void *p; };
Then each time you malloc pointer, you also write the size in the size field. However, the problem with this method is that you must point to a pointer every time you use it. If you were in C ++, I would suggest using template classes. However, in this case, it is not difficult, just create as many structures as you have. For example,
struct charPtr { size_t size; char *p; }; struct intPtr { size_t size; int *p; }; struct objectPtr { size_t size; struct object *p; };
Given similar names, once you define a pointer, you donβt need extra effort (like casting) to access the array. Usage example:
struct intPtr array; array.p = malloc(1000 * sizeof *array.p); array.size = array.p?1000:0; ... for (i = 0; i < array.size; ++i) printf("%s%d", i?" ":"", array.p[i]); printf("\n");
Shahbaz Aug 26 '11 at 8:59 2011-08-26 08:59
source share