Re: When/why to use size_t
- From: "Malcolm" <regniztar@xxxxxxxxxxxxxx>
- Date: Tue, 23 May 2006 20:56:56 +0100
"Alex Vinokur" <alexvn@xxxxxxxxxxxxxxxxxxxxx> wrote
Why was the size_t type defined in compilers in addition to unsignedsize_t is an uglification of the C language.
int/long?
When/why should one use size_t?
A bit like const or noalias, it seems sensible at first sight, but the
implicatins weren't thought through.
OK. Someone might want to allocate more memory than will fit in an int. So
make malloc() take a size_t.
Note that if an int is, as is the intention, the natural size for an integer
on that platform, one needs to ask how an amount of memory can fail to fit
in a register. But pass that by.
So now a string can be szie_t bytes long. So all the string functions need
to take size_t instead of integers, and return them.
Then it gets worse. Any array could have been allocated with malloc(). So
now all you array indices are size_t. So all the counts of array sizes are
size_t as well. So anything that is the result of an operation of a count of
things in the computer is a size_t. So integers virtually disappear from
your code. size_t has run through it.
But size_t's are unsigned. This introduces subtle problems into code.
For instance if we count down a loop
while(N-- > 0)
sudenly the code breaks, because N is of course a count of something, and so
a size_t.
Also, what if we want to subtract two size_ts, for instnace in computing x y
coordinates fro graphics?
It also becomes harder to validate parameters. Image dimensions cannot be
negative. Therefore
void myimagefunction(unsigned char *rgb, int width, int height)
{
assert(width >= 0);
assert(height >= 0)
}
if we are passed random garbage to this function there is a 75% percent
chance of the assets triggering. if the function is called more than a few
times with random garbage, the chance of the assert triggering is
effectively certain.
However width and height are indices, so they've got to be size_t's, since
the image buffer is allocated with malloc().
size_t is a terrible idea that has no place in C code.
--
Buy my book 12 Common Atheist Arguments (refuted)
$1.25 download or $7.20 paper, available www.lulu.com/bgy1mm
.
- Follow-Ups:
- Re: When/why to use size_t
- From: Joe Smith
- Re: When/why to use size_t
- From: Keith Thompson
- Re: When/why to use size_t
- From: Richard Heathfield
- Re: When/why to use size_t
- References:
- When/why to use size_t
- From: Alex Vinokur
- When/why to use size_t
- Prev by Date: Re: GTK Libraries in WIndows
- Next by Date: Re: General rules on interface (function) design
- Previous by thread: Re: When/why to use size_t
- Next by thread: Re: When/why to use size_t
- Index(es):
Relevant Pages
|
Loading