Why using X is (such?) a bad habit
As some of you may know, I am a C-Unix (among others subjects) teacher assistant at my current school (EPITECH). When students come to defend their project, one of the reason of loosing point is to not check the return value of system call inside their code (-2 points each time one syscall’s return value is not checked).
As a result, some students has come of what they think to be a great idea (or I’ve been told so): the X functions. I’m going to pick the worst case of utilisation of this: xmalloc.
void *xmalloc(size_t size)
{
void *buff;
buff = malloc(size);
if (buff == NULL)
{
//EDIT: this is bad
// fprintf(stderr, "not enough memory\\n");
//EDIT: kind of better
write(1, "not enough memory\\n", 18);
exit(1);
}
return (buff);
}
Well, in this implementation I’ve been kind enough to print an error message before exiting, some students doesn’t bored to do this much.
So, what is the problem of using this alternative to malloc? It’s pretty obvious if you’re asking me. I’m going to give a couple of examples:
First:
Let’s imagine that an application like Firefox rely on this kind of function (and I hope it doesn’t). Would you be glad if, you’ve been using your browser since several hours, having open several tabs and upon trying to open a new one boum ! “not enough memory” and Firefox exit. All your search lost… forever.
My point is that an application should never exit like that if she can still continue to work or manager its currents state. For example you should still be able to read your current tabs. But what if another error occurs ? Well one of the option is to allocate ressources to display error message at the beginning of the application to minize the case where you will not even be able to warn the user about the occurring problem.
But let switch to my second point:
This one is surely more cynicale. Take the case of an Operating system. Imagine that it can not found enough resources to start a task and just shutdown. Will that make you happy? I guess I don’t need to said anymore to prove this case ;).
So, please:
- Check you syscall’s return values
- Don’t quit upon failure if you can still manage to go on with your current state
- Warn the user about the problem and give him the choise about what to do (going on or quit, etc).
I’ve got something more to tell about this xmalloc things, but I’ll keep it for another time. I’ve got to keep an eye on my students tonight :).