small views of large files
Here are three new lines, after the patch.
unsigned int buflen = strlen(hbuf) + strlen(cp2) + 1; cp = (char *)malloc(sizeof(char)*buflen); snprintf((char *)cp, buflen, "%s%s", hbuf, cp2);
1. The first line is indented with spaces while the others use tabs.
2. The correct type for string length is
sizeof(char) is always one. There’s no need to multiply by it.
4. If you do need to multiply by a size, this is an unsafe pattern. Use
calloc or something similar. (OpenBSD provides
reallocarray to avoid zeroing cost of calloc.)
5. Return value of
malloc doesn’t need to be cast. In fact, should not be, lest you disguise a warning.
6. Return value of
malloc is not checked for NULL.
7. No reason to cast
char * when passing to
snprintf. It already is that type. And if it weren’t, what are you doing?
8. The whole operation could be simplified by using
9. Although unlikely (probably impossible here, but more generally), adding the two source lengths together can overflow, resulting in truncation with an unchecked
asprintf avoids this failure case.
For starters, we might look at this fine patch removing alloca from a function in glibc. I’m mostly interested in the first chunk. That’s quite the incantation to prototype a function.
Another variant of the alloca spellbook is in bash. This version supports a different set of operating systems.
As Ben Franklin never said, “Beer is proof God loves us and wants us to be happy.” The ifdef maze one encounters trying to call alloca is proof your compiler hates you and you will be unhappy.