5 ms·
buf = calloc(huge, huge); if (errno) perror("calloc failed"); printf("calloc(huge, huge) returned: %p\n", buf); free(buf); This has a flaw. errno d
by _RPM 10y ago
buf = calloc(huge, huge);
if (errno) perror("calloc failed");
printf("calloc(huge, huge) returned: %p\n", buf);
free(buf);
This has a flaw. errno doesn't magically get reset to zero. You should check the return value of calloc, then use errno. Checking if(errno) is not the right way to determine if there was an error.
- avar 10y agoIts [errno's] value is significant only when the return value of the call indicated an error (i.e., -1 from most calls; -1 or NULL from most library functions); a function that succeeds is allowed to change errno.
- imron 10y agoNote the difference between "is allowed" vs "must". If you write a program that relies on this behaviour you're going to have a hard to track down bug at some point.
- takeda 10y agoThat's even stronger case for not relying on errno to catch errors. The code should be something like this: buf = calloc(huge, huge); if (!buf) perror("calloc failed"); printf("calloc(huge, huge) returned: %p\n", buf); free(buf);
- ericfrederich 10y agoYeah... that caught my attention too and I looked up errno and found the same thing.
- int0x80 10y agowow, yeah, that's totally and obviously buggy ...