3 ms·
- The pattern "x = realloc(x, ...)" is a bad idea, it leaks the original memory on failure. Since the code seems to car about its memory management (and since i
by userbinator 10y ago
- The pattern "x = realloc(x, ...)" is a bad idea, it leaks the original memory on failure. Since the code seems to car about its memory management (and since it's a tutorial), I think this is worth mentioning (and fixing).
If you look at what the code does after that...
if (!buffer) {
fprintf(stderr, "lsh: allocation error\n");
exit(EXIT_FAILURE);
}
...there is nothing to "fix" because there is nothing more the code can do --- the whole process is gone after that; unless you imply getting into the intricacies of trying to recover from out-of-memory situations, which quickly opens its own huge can of worms (does fprintf() itself do an allocation? Could that allocation fail? What to do if printing the error message fails? Etc. etc.)
In general, I think the "this pattern is bad" sort of "thinking" is itself a bad idea; when writing and examining code, you should be looking at each situation itself and thinking to evaluate it, not just trying to match everything into one "pattern" or another. Does "x = realloc(x, ...)" make sense in all contexts? No. Does it make sense here? Yes. Otherwise it is a path towards mindless cargo-cultism, something which beginners should certainly be discouraged from doing.
- unwind 10y agoYeah, good point about the exit(), I realized that and mentioned it in a later comment (below). I do really try to look at the situation, but that doesn't change the fact (at least in my experience) that there are patterns of "bad code" that seem to have a life of their own. Probably caused by things being unintuitive, and/or more complex than people first realize, or something. I'm really opposed to cargo cult programming, so no argument there. :)