I'm very confused about void pointers and this notation here below. I do understand that when you have a void pointer you eventually cast it to some kind of type int, double. What I don't understand is what is happening here : copySize = *(size_t *)((char *)oldptr - SIZE_T_SIZE);

copySize is of type size_t and then we make it equal to oldptr casted to a char?

here is the whole code snipped. I would be very graceful for some "pointers" here ;)

void *mm_realloc(void *ptr, size_t size)
{
    void *oldptr = ptr;
    void *newptr;
    size_t copySize;

    newptr = mm_malloc(size);
    if (newptr == NULL)
      return NULL;
    copySize = *(size_t *)((char *)oldptr - SIZE_T_SIZE);
    if (size < copySize)
      copySize = size;
    memcpy(newptr, oldptr, copySize);
    mm_free(oldptr);
    return newptr;
}

(char *)oldptr
Pretend oldptr is a pointer to a char (a char is one byte, by definition in C)...

- SIZE_T_SIZE
and change its value to point SIZE_T_SIZE bytes earlier...

(size_t *)
and now pretend it's not pointing at a char anymore, instead pretend it's pointing at a size_t type

*
and dereference it to give me that size_t type...

copySize =
and set the value of copySize to that value.

Ahh ok I see, so this means that the void pointer passed to the function has to be assigned to a char right?, and that's why it's changing it's pointer from a char to size_t?

The aim of this code is to take a pointer, move backwards SIZE_T_SIZE bytes (which I'm guessing is the size on a single object of type size_t), and then interpret what that now points at as a size_t object.

The cast to char happens because you cannot conduct pointer arithmetic on a void-pointer (there is a gcc extension to do it, but it's a non-standard thing and as such should be avoided).

ahh ok I understand now, thank you very much for a good explanation :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.