Коллеги снабдили замечательной ссылкой
Цитата:
Here's a real life example written by a master. Let's look at all the
different techniques he packed into this single C function:
Reinvent simple functions which are part of the standard libraries.
The word Realocate is not spelled correctly. Never underestimate the
power of creative spelling.
Make a temporary copy of input buffer for no real reason.
Cast things for no reason. memcpy() takes (void*), so cast our pointers even
though they're already (void*). Bonus for the fact that you could pass anything
anyway.
Never bothered to free temp. This will cause a slow memory leak, that may not
show up until the program has been running for days.
Copy more than necessary from the buffer just in case. This will only cause a
core dump on Unix, not Windows.
It should be obvious that os and ns stand for "old size" and "new
size".
After allocating buf, memset it to 0. Don't use calloc() because somebody might
rewrite the ANSI spec so that calloc() fills the buffer with something other
than 0. (Never mind the fact that we're about to copy exactly the same amount
of data into buf.)
Цитата:
Here's a real life example written by a master. Let's look at all the
different techniques he packed into this single C function:
void* Realocate(void*buf, int os, int ns)
{
void*temp;
temp = malloc(os);
memcpy((void*)temp, (void*)buf, os);
free(buf);
buf = malloc(ns);
memset(buf, 0, ns);
memcpy((void*)buf, (void*)temp, ns);
return buf;
}
Reinvent simple functions which are part of the standard libraries.
The word Realocate is not spelled correctly. Never underestimate the
power of creative spelling.
Make a temporary copy of input buffer for no real reason.
Cast things for no reason. memcpy() takes (void*), so cast our pointers even
though they're already (void*). Bonus for the fact that you could pass anything
anyway.
Never bothered to free temp. This will cause a slow memory leak, that may not
show up until the program has been running for days.
Copy more than necessary from the buffer just in case. This will only cause a
core dump on Unix, not Windows.
It should be obvious that os and ns stand for "old size" and "new
size".
After allocating buf, memset it to 0. Don't use calloc() because somebody might
rewrite the ANSI spec so that calloc() fills the buffer with something other
than 0. (Never mind the fact that we're about to copy exactly the same amount
of data into buf.)
(no subject)
Date: 2005-03-22 03:25 am (UTC)странно, что там не было классического:
#define i j
// happy debugging!