lkml.org 
[lkml]   [2000]   [Nov]   [7]   [last100]   RSS Feed
Views: [wrap][no wrap]   [headers]  [forward] 
 
Messages in this thread
/
SubjectRe: malloc(1/0) ??
Date
From
Matti Aarnio wrote:
> needed size is bound to get user burned. malloc(0) is insane thing
> (IMO), but at least glibc supports it for some reason. Likely just due
> to padding and minimum size issues.

Part of the desing of the C language and the library is intended to
make boundary conditions go well automatically.

So, a program that does:

fscanf (file, "%d", &numsquares);
squares = malloc (sizeof (struct square) * numsquares);
for (i=0;i<numsquares; i++)
read_square_from_file (file, &squares[i]);

fscanf (file, "%d", &numtriangles);
triangles = malloc (sizeof (struct triangle) * numtriangles);
for (i=0;i<numtriangles; i++)
read_triangle_from_file (file, &triangles[i]);


[use the stuff....]

free (triangles);
free (squares);

should work. See, the "for" loop nicely executes 0 times when
numtriangles is zero. Similarly, malloc/free don't have any
"exception" case for the "numtriangles is zero" case.

Now, at first you might say that "malloc" could return NULL, as long
as "free" accepts it. However, that's not true: The result of the
malloc call can and acutally should be checked for "NULL", and the
program might abort.

A valid implementation MAY:


#define NIL ((void *) 1)

void * malloc (int size)
{
if (size == 0) NIL;
[....]
}

void free (void *ptr)
{
if (ptr == NIL) return;
[...]
}

This way all should work. However someone mentioned that the returns
from "malloc" should be unique. Why would that be? That would prohibit
my "1" trick. The statement implies you want to go about checking
pointers for equality. If for example you have a memcmp (a, b) that
has "if (a == b) return 0;" at the beginning. That would be allowed
for the NIL pointers. (all malloc-0 results SHOULD compare equal
anyway: there are 0 differences....)

Roger.

--
** R.E.Wolff@BitWizard.nl ** http://www.BitWizard.nl/ ** +31-15-2137555 **
*-- BitWizard writes Linux device drivers for any device you may have! --*
* Common sense is the collection of *
****** prejudices acquired by age eighteen. -- Albert Einstein ********
-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@vger.kernel.org
Please read the FAQ at http://www.tux.org/lkml/

\
 
 \ /
  Last update: 2005-03-22 12:45    [W:0.096 / U:0.508 seconds]
©2003-2020 Jasper Spaans|hosted at Digital Ocean and TransIP|Read the blog|Advertise on this site