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.
sizeofofmalloc-allocated array. You could get it in some cases from the metadata of the allocated block, but it is implementation specific.sizeofis 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 (likesizeof(int)), but they are not needed for general expressions (likesizeof my_int_variable).reallocin isolation, then it is virtually impossible without getting into the specific implementation internals.reallocwithout also implementingmalloc,callocandfree--- unless you are tied to one implementation ofmallocand can use its internal workings (which you will need to discover through documentation, source code, or if all else fails, experimentation).reallocstand-alone, then I'd question the teacher's competence.