FAQ - malloc array - clarify

Peter Holzer hp at vmars.tuwien.ac.at
Wed Sep 12 01:16:56 AEST 1990


cpcahil at virtech.uucp (Conor P. Cahill) writes:

>In article <1803 at tuvie> hp at vmars.tuwien.ac.at (Peter Holzer) writes:
>>cpcahil at virtech.uucp (Conor P. Cahill) writes:
>>
>>>This is caused by the argument to malloc being unsigned, not signed.  A
>>>cast in your code will fix this.
>>
>>No! Don't fix your code, which is correct. Fix the lint library.
>>The argument to malloc should be the type returned by sizeof (): size_t
>>(an unsigned integral type).

>The argument to malloc is defined in the library (i.e. where malloc()
>is encoded).  running lint against the source builds the lint library and
>therefore the lint library will correctly reflect what the code has (besides,
>without code, you can rebuild a lint library).

The lint libraries are ASCII files on our system. Are they in a compiled 
form on yours ?

>The problem that the original poster ran into is that on his system
>the type of sizeof() is an integer.  However, the type of malloc's 
>argument is an unsigned integer.

We have the same problem on our machines (DECstations, Ultrix 2.1, cc 1.31),
but I use gcc, so I didn't run across it before:

In <sys/types.h>:
	typedef int size_t;	/* returned by sizeof */
				/* this is a compiler bug.
				   should be unsigned	*/
In /usr/lib/lint/llib-lc:
	char *    malloc(n) unsigned n; {static char c; return(&c);}

Exactly the situation described. Now if I want to shut up lint about
foop = malloc (sizeof (struct foo));
what should I cast the argument to malloc to?
*   Unsigned is not a good choice. On the next system I want to port my program
    to, malloc might be declared char * malloc (unsigned long n); and if int
    and long are different sizes I might not get what I want. 
*   Unsigned long is even worse. It might not even work on the machine I use
    now.
*   Size_t is the type I have already.
*   Any other ideas ?

So what I propose is the following:
Check if the non-negative values of int have the same representation as the 
corresponding values of unsigned ints (This is true for all machines I know,
and is guarantueed for ANSI C). If this holds, it does not matter if you are
passing a non-negative int or an unsigned to a function expecting unsigned.

Because of this you can change the above line in llib-lc to:
char *    malloc(n) int n; {static char c; return(&c);}

I know this is a hack, but it is a hack that does not force you to write
non-portable programs, as the cast-workaround does.

(The other possibility is not to use lint, which I am forced to do, because
lint gags on my prototypes, but in general, I would not recommend that).
--
|    _	| Peter J. Holzer			| Think of it	|
| |_|_)	| Technische Universitaet Wien		| as evolution	|
| | |	| hp at vmars.tuwien.ac.at			| in action!	|
| __/  	| ...!uunet!mcsun!tuvie!vmars!hp	|     Tony Rand	|



More information about the Comp.lang.c mailing list