Search code examples
cmallocsizeofdynamic-arraysrealloc

Is there any way at all to get the size of a dynamic array with sizeof()?


I'm a computer science student and one of the questions on a test asked to implement realloc in C using malloc. My teacher said the correct answer would be to get the sizeof of the previous array and compare to the new size before copying the elements of the previous array.

I asked him if the sizeof function could actually do that and he said it could but I couldn't find it anywhere. Sorry if this is a duplicate or similar to another question but I need to be sure.


Solution

  • Your teacher is wrong on this.

    Most uses of sizeof are evaluated only at compile-time (the exception is VLAs, which malloc doesn't deal with). As such, sizeof does not work on malloc'ed memory that is allocated at runtime.

    You would need to implement malloc and store the allocated size as a hidden field inside the memory block itself in order for your realloc to be able to query it later.