Edit: Correction, some people are bashing me for what I said, the way you allocated your pointer seems to be best practice among them, I was taught to always go with type casts in the sizeof()
, but apparently your way is more correct, so disregard what I said =)
Taking a peek at http://en.wikipedia.org/wiki/Malloc#realloc before might have done you some good.
You don't quite understand sizeof()
- it has the value of the size of the argument you pass to it in bytes. For example, sizeof(int)
will be 4 on most 32 bit systems but you should still use sizeof(int)
instead of 4
because compiling your code on a 64 bit system (just as an example) will make that value equal to 8 and your code will still compile fine. What are you allocating memory for? Pointers? If so you should use sizeof(void*)
instead (you can say sizeof(int*)
but it's common convention not to mention to the compiler what you want to store at those pointers, since all pointers should be the same size - so most programmers say sizeof(void*)
), if you need space for characters use sizeof(char)
and so on.
You are however right to store the return value of realloc()
in a new pointer and check it, though a lot of programmers will assume the system always has enough memory and get away with it.