Search code examples
cdynamic-memory-allocation

How to get size of different kinds of types in the same function using C?


I'm writing a function which increases the size of a dynamic memory object created with malloc. The function should as arguments take a pointer to the memory block to be increased, the current size of the block and the amount the block is going to be increased.

Something like this:

int getMoreSpace(void **pnt, int size, int add) {
    xxxxxx *tmp; /* a pointer to the same as pnt */
    if (tmp = realloc(pnt, (size+add)*sizeof(xxxxxx))) { /* get size of what pnt points to */
        *pnt=tmp;
        return 1;
    else return 0;
}

The problem is that I want the function to work no matter what pnt points to. How do I achieve that?


Solution

  • This type of function cannot possibly work, because pnt is local and the new pointer is lost as soon as the function returns. You could take an argument of type xxxxxx ** so that you could update the pointer, but then you're stuck with only supporting a single type.

    The real problem is that you're writing an unnecessary and harmful wrapper for realloc. Simply use realloc directly as it was meant to be used. There is no way to make it simpler or more efficient by wrapping it; it's already as simple as possible.