0

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.

7
  • 1
    No, you can't get sizeof of malloc-allocated array. You could get it in some cases from the metadata of the allocated block, but it is implementation specific. Commented Nov 22, 2024 at 15:40
  • 3
    Nitpicking: sizeof is an operator not a function. It's no different from e.g. the pointer-to operator & (well, except its behavior). The confusion usually comes from the need to use parentheses for type-names (like sizeof(int)), but they are not needed for general expressions (like sizeof my_int_variable). Commented Nov 22, 2024 at 15:41
  • 1
    @pmg If the ask is to re-implement realloc in isolation, then it is virtually impossible without getting into the specific implementation internals. Commented Nov 22, 2024 at 15:48
  • 3
    It is not possible to implement realloc without also implementing malloc, calloc and free --- unless you are tied to one implementation of malloc and can use its internal workings (which you will need to discover through documentation, source code, or if all else fails, experimentation). Commented Nov 22, 2024 at 16:33
  • 4
    If this is really a question in exam, and it requires to re-implement realloc stand-alone, then I'd question the teacher's competence. Commented Nov 22, 2024 at 17:19

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.