Quote:
Originally Posted by
alister
Unrelated to the segfault, there are a couple of things about this statement of which you should be aware.
In general, if you're going to multiply a number by the size of a data type, you should use calloc(). If not, you should check for overflow before passing the result to malloc(). I say in general because in this specific instance, where the number is hardcoded and the product is almost certainly less than the max value of size_t, it's extremely unlikely that it will cause a problem.
Why calloc? It zeros the memory and, as such, will touch every page allocated, forcing the kernel to actually create a physical page for it. This is wasteful, IMO, especially if you'll be writing to that memory again immediately (as he is) or, worse, if you'll be writing to the memory sparsely. Plus, I always thought that "calloc(x, y)" was pretty much equivalent to "malloc(x*y)" minus the obvious zeroing of the returned memory.
Quote:
Originally Posted by
alister
Unless you know why you're doing it, it's best not to cast unnecessarily. Many C programmers do it unthinkningly, but it is a practice with zero benefit and a potentially insidious drawback: supression of compiler warnings and errors.
If the malloc implementation does not return void * (or in this instance * char), the explicit cast tells the compiler that its okay if malloc returns an int (which is not unheard of) or some other type, and, should such a mismatch occur, that you want it to silently coerce the return value regardless of its type. Such coercion can lead to unexpected behavior.
Regards,
Alister
I've never seen a malloc implementation return int, but since the compiler assumes any functions that it hasn't seen a definition for take integer parms and return int, casting is a good way to step on your foot if you forget to include the header for malloc, lol. I've seen this before, and it's not pretty when someone spends forever trying to debug a core dump due to the compilers' (mis)understanding that malloc returns int and sign extends the result badly into the pointer causing its value to be incorrect and, thusly, causing a crash. All warnings were suppressed because of the cast. (BTW, it wasn't me, lol. I was the one who noticed stdlib wasn't included, and upon me were bestowed many thanks, lol). Of course, to this day I still have to force myself not to cast the result of malloc, but that day inspired me to stop doing it.