Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

malloc question

11 views
Skip to first unread message

thief

unread,
Aug 10, 1995, 3:00:00 AM8/10/95
to
Hi can anyone help?
-----------------------------
struct rec {
char a;
struct rec *next;
};
struct rec *p;
-------------------------------

The above is my declaration,can anyone explains the difference between

p=(struct rec *) malloc(sizeof(struct rec));

and

p=malloc(sizeof(struct rec));

I could not compile with the second statement in my program.


--

( ( (
...Jupiter... ) ) ) My greatest glory
( ( ( is not in never falling,
'. ___ .' but in rising every time I fall.
' (> <) '
----bo...@iscs.nus.sg----ooO-(_)-Ooo--http://www.iscs.nus.sg/~boochinp---

Tanmoy Bhattacharya

unread,
Aug 10, 1995, 3:00:00 AM8/10/95
to
In article <40d2vv$f...@nuscc.nus.sg>, booc...@iscs.nus.sg (thief) writes:
<snip>

|> The above is my declaration,can anyone explains the difference between
|>
|> p=(struct rec *) malloc(sizeof(struct rec));
|>
|> and
|>
|> p=malloc(sizeof(struct rec));
|>
|> I could not compile with the second statement in my program.

A cast often hides other mistakes: The `right' was to use malloc is to
#include <stdlib.h> first. With a cast, the compiler will not complain if in
fact you forget to include <stdlib.h>, the program will however crash on
some platforms.

If the second still gives an error, you are not using a C compiler. Remember
comp.lang.c is not comp.lang.c++.

Cheers
Tanmoy
--
tan...@qcd.lanl.gov(128.165.23.46) DECNET: BETA::"tan...@lanl.gov"(1.218=1242)
Tanmoy Bhattacharya O:T-8(MS B285)LANL,NM87544-0285,USA H:#3,802,9 St,NM87545
Others see <gopher://yaleinfo.yale.edu:7700/00/Internet-People/internet-mail>,
<http://alpha.acast.nova.edu/cgi-bin/inmgq.pl>or<ftp://csd4.csd.uwm.edu/pub/
internetwork-mail-guide>. -- <http://nqcd.lanl.gov/people/tanmoy/tanmoy.html>
fax: 1 (505) 665 3003 voice: 1 (505) 665 4733 [ Home: 1 (505) 662 5596 ]

Glenn Carr

unread,
Aug 11, 1995, 3:00:00 AM8/11/95
to
booc...@iscs.nus.sg (thief) wrote:
>Hi can anyone help?
>-----------------------------
>struct rec {
> char a;
> struct rec *next;
>};
>struct rec *p;
>-------------------------------
>
>The above is my declaration,can anyone explains the difference between
>
>p=(struct rec *) malloc(sizeof(struct rec));
>
>and
>
>p=malloc(sizeof(struct rec));
>
>I could not compile with the second statement in my program.
>

malloc is returns a char* by default, so you have to cast its return value or
most compilers will complain.

--
Glenn Carr, gc...@lgc.com, 71553...@compuserve.com
[Munro Garrett International, A Landmark Graphics Company]


Tanmoy Bhattacharya

unread,
Aug 11, 1995, 3:00:00 AM8/11/95
to
In article <40g5j7$5...@dildog.lgc.com>, Glenn Carr <Glenn...@lgc.com>
writes:
<snip>

|> malloc is returns a char* by default, so you have to cast its return value
or
|> most compilers will complain.

Not in C :-)

Okay, I will admit that in a now obsolete language which was described in a
book by K&R called C at that time, malloc used to return a char*. (And not
only by default: it _always_ returned a char*. You were probably allowed to
write your own char* to return struct bublaboo, but we are not talking about
those.) However, malloc still needed to be declared before use.

An august body of men (were there any women in the committee?) sat down and
properly defined the language for the first time. The second edition of the
book aforementioned defined this language instead. It is called ANSI C when
one has to distinguish it from the previous one, which is somewhat
confusingly often called K&R C.

But the fact remains that unless it is explicitly mentioned, C refers to the
current language ANSI C. In this, a cast on the return value of malloc is
useless; and can often mask other mistakes like forgetting to include
<stdlib.h> (and not otherwise declaring malloc).

In C++, the cast is probably required. But in C++, one would probably use the
new operator rather than malloc.

Derick J.R. Qua-Gonzalez

unread,
Aug 12, 1995, 3:00:00 AM8/12/95
to
Glenn Carr <Glenn...@lgc.com> writes:

>malloc is returns a char* by default, so you have to cast its return value or
>most compilers will complain.

No Glenn, it does not. The return value of malloc is void*.

Best regards,
Derick.
--
+-----------------------------------------------------------------------------+
| Derick R. Qua-Gonzalez | ________ |
| Department of High Energy Physics, California State University | \ / |
| dq...@dqua.EarthLink.Net | \ / |
| ``It is better to be hated for what one is, | \ / |
| than loved for what one is not.'' (A. Gide) | G \/ USA|
+------------------------------------------------------------------+----------+

Martin Ambuhl

unread,
Aug 12, 1995, 3:00:00 AM8/12/95
to
Glenn Carr <Glenn...@lgc.com> in <40g5j7$5...@dildog.lgc.com> writes:

>malloc is returns a char* by default, so you have to cast its return value or
>most compilers will complain.

Unless "most" compilers are non-conforming, the truth value for each
part of the above is 0.

1. The ISO/ANSI prototype for malloc is
void *malloc(size_t size).
2. Casting the return value will mask real errors (like forgetting to
#include <stdlib.h>).
3. ANSI-compliant compilers will not complain.

I rarely see an "answer" in c.l.c that is completely vacuous, but Mr.
Carr has managed it.
--
* Martin Ambuhl net: mam...@ripco.com
* Chicago, IL (USA)

Dan Pop

unread,
Aug 12, 1995, 3:00:00 AM8/12/95
to
In <40g5j7$5...@dildog.lgc.com> Glenn Carr <Glenn...@lgc.com> writes:

>booc...@iscs.nus.sg (thief) wrote:
>>
>>The above is my declaration,can anyone explains the difference between
>>
>>p=(struct rec *) malloc(sizeof(struct rec));
>>
>>and
>>
>>p=malloc(sizeof(struct rec));
>>
>>I could not compile with the second statement in my program.
>>
>

>malloc is returns a char* by default, so you have to cast its return value or
>most compilers will complain.

^^^^
Two major mistakes in a single phrase:

1. malloc returns a void *, period. (What do you mean by "by default"?).

2. The value returned by malloc shouldn't be cast. A void pointer is
automatically converted by the compiler to any other kind of object
pointer. By casting malloc, all you achieve is hiding the errors
caused by calling malloc without a declaration or prototype in scope.
If the compiler complains about an uncast malloc, it is because the
program is broken (no declaration for malloc, which doesn't return
int) and the right thing is _not_ to cast malloc, but to declare it
or, even better, to include <stdlib.h>.

Note that this discussion applies to the current definition of the C
language. K&R C had no void pointers, so malloc indeed returned a char *
and a cast was required whenever the result was assigned to a different
kind of object pointer. K&R C compilers are nowadays the exception, so
the usage of the word "most" by the previous poster was gratuitous.

Dan
--
Dan Pop
CERN, CN Division
Email: Dan...@mail.cern.ch
Mail: CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland

Bob Nelson

unread,
Aug 15, 1995, 3:00:00 AM8/15/95
to
On Sat, 12 Aug 1995, Dan Pop (Dan...@mail.cern.ch) wrote:

> 1). malloc returns a void *, period.
>
> 2). The value returned by malloc shouldn't be cast. A void pointer is


> automatically converted by the compiler to any other kind of object
> pointer. By casting malloc, all you achieve is hiding the errors
> caused by calling malloc without a declaration or prototype in scope.
> If the compiler complains about an uncast malloc, it is because the
> program is broken (no declaration for malloc, which doesn't return
> int) and the right thing is _not_ to cast malloc, but to declare it
> or, even better, to include <stdlib.h>.

[Statements about the current C definition (void *malloc) vs. K&R C
(char *malloc) elided].

Mr. Pop, sir, a book that I like to refer to frequently that purports
to deal with the current definition of the C language makes the following
statement: "In C, the proper method is to declare that malloc returns a
pointer to void, then _explicitly_ [emphasis added] coerce the pointer
into the desired type with a cast."

As of Saturday, 12 August 1995, I've come to believe that this book must
be in error since you state that the "value returned by malloc shouldn't
be cast" which naturally follows from your first point about it
returning a pointer to void. Oh my, that wacky book! What a hoot! It
correctly acknowledges that malloc returns a pointer to void...but then
says to cast it anyway. To make matters worse, they even *show examples*
of malloc _with_ a cast!

I believe the authors of the rather slim book, in contrast to your
impressive CERN/Geneva credentials, were just employees for some phone
outfit in a little New Jersey town. These guys at least had the good
sense to agree with you about <stdlib.h> so maybe the book has *some*
redeeming qualities.

--
=============================================================================
Bob Nelson: Dallas, Texas, U.S.A. - bne...@netcom.com
Linux for fun, M$ for $$$...and the NFL for what really counts!
=============================================================================


George Varndell

unread,
Aug 15, 1995, 3:00:00 AM8/15/95
to
An uneasy silence fell over c.l.c...
Bob had thrown down the gauntlet.
And everyone knew Dan was sharpening his sabre.


Tanmoy Bhattacharya

unread,
Aug 15, 1995, 3:00:00 AM8/15/95
to
In article <bnelsonD...@netcom.com>, bne...@netcom.com (Bob Nelson)
writes:
<snip>

|> Mr. Pop, sir, a book that I like to refer to frequently that purports
|> to deal with the current definition of the C language makes the following
|> statement: "In C, the proper method is to declare that malloc returns a
|> pointer to void, then _explicitly_ [emphasis added] coerce the pointer
|> into the desired type with a cast."

I have made no attempt to look this up, and am assuming that the above is a
full and complete representation of the statements made there.

There are times even the best of books come up with examples and advice which
is difficult to defend. I have seen a lot of people using casts on the return
value of malloc and suppressing a warning message (thus ending up with an
incorrect program). Very few, if any, programs got a warning _because_ the
cast exposed a conceptual confusion about what type the lhs was.

As the former is a common mistake, I would advise the omission of the cast on
the return value of malloc; unless portability to pre-ANSI C is important
(and unless it is the extremeley odd case that the result of malloc is being
passed directly to a function without prototype, or in the variable portion
of a vararg function). As any advice, this may be ignored: but if I came
across two advices one telling me to be careful (`do not cast'), and the
other telling me to switch off the error checking (`cast the result of
malloc'), irrespective of authority, I would choose the first.

Bob Nelson

unread,
Aug 15, 1995, 3:00:00 AM8/15/95
to

Yes...it is much like the eye of the hurricane over c.l.c. All appears
calm and quiet. But rather than boarding the windows or putting on my
protective armor -- I continue to read that book by those two guys from
Jersey. Yes...I am a condemned man...marking time...reading that book.
(Maybe the press was "broken" as this instance of the volume was printed
and the key section is missing that affirms Mr. Pop's contention that
"the value from malloc shouldn't be cast.")

I only plead that Mr. Pop's sabre be swift as he pierces this humble
reader who dare challenge him. (I am reminded of the trembling quartet
[and Toto, too] as they cower in awe of the mighty Oz).

Nervously, I turned to a page a little bit later in the rather thin
book (the authors seem a bit proud that it is not a "big book"), they
say [7.8.5]: "The pointer returned by malloc or calloc has the proper
alignment for the object in question, but it must be _cast_ [again,
emphasis added] into the appropriate type...". This is followed by
an example. It is in a section [7.8] that begins with the statement:
"The standard library provides a wide variety of functions."

Steve Summit

unread,
Aug 15, 1995, 3:00:00 AM8/15/95
to
In article <bnelsonD...@netcom.com>, bne...@netcom.com
(Bob Nelson) writes:
> On Sat, 12 Aug 1995, Dan Pop (Dan...@mail.cern.ch) wrote:
>> 2). The value returned by malloc shouldn't be cast...

>
> Mr. Pop, sir, a book that I like to refer to frequently that purports
> to deal with the current definition of the C language makes the following
> statement: "In C, the proper method is to declare that malloc returns a
> pointer to void, then _explicitly_ [emphasis added] coerce the pointer
> into the desired type with a cast."

I think I know what book you're talking about. Note that that
book only "deal[s] with the current definition of the C language";
it is not itself the current definition of the C language.

> As of Saturday, 12 August 1995, I've come to believe that this book must

> be in error...

You are correct. In fact, someone who had communicated with one
of that book's authors on this very point suggested that I
explicitly mention the discrepancy in the comp.lang.c FAQ list,
which addresses the issue in its current question 3.5. The
book's author is quoted as admitting that the book's language
about casting malloc is "overenthusiastic."

> ...Oh my, that wacky book! What a hoot! It


> correctly acknowledges that malloc returns a pointer to void...but then
> says to cast it anyway. To make matters worse, they even *show examples*
> of malloc _with_ a cast!

There is, of course, no prohibition against using explicit casts,
and they are useful if portability to pre-ANSI compilers and
lints is important. (The authors of that "wacky book," as you
might imagine, are somewhat biased towards pre-ANSI, K&R
compilers.) To be sure, as has already been noted, explicit
casts do tend to mask warnings about inadvertent misdeclarations
of malloc.

Steve Summit
s...@eskimo.com

Dan Pop

unread,
Aug 15, 1995, 3:00:00 AM8/15/95
to
In <bnelsonD...@netcom.com> bne...@netcom.com (Bob Nelson) writes:

>On Sat, 12 Aug 1995, Dan Pop (Dan...@mail.cern.ch) wrote:
>

>> 1). malloc returns a void *, period.
>>
>> 2). The value returned by malloc shouldn't be cast. A void pointer is
>> automatically converted by the compiler to any other kind of object
>> pointer. By casting malloc, all you achieve is hiding the errors
>> caused by calling malloc without a declaration or prototype in scope.
>> If the compiler complains about an uncast malloc, it is because the
>> program is broken (no declaration for malloc, which doesn't return
>> int) and the right thing is _not_ to cast malloc, but to declare it
>> or, even better, to include <stdlib.h>.
>[Statements about the current C definition (void *malloc) vs. K&R C
>(char *malloc) elided].
>

>Mr. Pop, sir, a book that I like to refer to frequently that purports
>to deal with the current definition of the C language makes the following
>statement: "In C, the proper method is to declare that malloc returns a
>pointer to void, then _explicitly_ [emphasis added] coerce the pointer
>into the desired type with a cast."

This is on page 142, right?

>As of Saturday, 12 August 1995, I've come to believe that this book must

>be in error since you state that the "value returned by malloc shouldn't
>be cast" which naturally follows from your first point about it

>returning a pointer to void. Oh my, that wacky book! What a hoot! It


>correctly acknowledges that malloc returns a pointer to void...but then
>says to cast it anyway. To make matters worse, they even *show examples*
>of malloc _with_ a cast!
>

>I believe the authors of the rather slim book, in contrast to your
>impressive CERN/Geneva credentials, were just employees for some phone
>outfit in a little New Jersey town. These guys at least had the good
>sense to agree with you about <stdlib.h> so maybe the book has *some*
>redeeming qualities.

Bob Nelson goofed again. Admitedly, his only fault is that he's not
a regular reader of c.l.c. Unfortunately, for him, I am. And I didn't
miss an article posted by Greg Black on 28 March 1995 in a thread
debating whether the value returned by malloc should be cast (somebody
used K&R2 against my arguments). Here's the relevant part:

# To save anybody from the embarrassment of leaping needlessly to the
# defence of K&R-2, I asked Dennis Ritchie for an opinion that I could
# quote on the validity of the sentence cited above from page 142. He
# replied:
#
# In any case, now that I reread the stuff on p. 142, I think it's
# wrong; it's written in such a way that it's not just defensive
# against earlier rules, it misrepresents the ANSI rules.

As I said in a previous post, I can use my brain so I'm not affraid to
disagree with anybody, no matter the credentials, when I know that my
arguments are strong enough. And arguments based on the C standard will
always beat any quote from _any_ C book, K&R2 included.

Waiting for Bob Nelson's next attack,

Lawrence Kirby

unread,
Aug 16, 1995, 3:00:00 AM8/16/95
to
In article <40qdvj$7...@newshost.lanl.gov>
tan...@qcd.lanl.gov "Tanmoy Bhattacharya" writes:

>In article <bnelsonD...@netcom.com>, bne...@netcom.com (Bob Nelson)
>writes:

><snip>


>|> Mr. Pop, sir, a book that I like to refer to frequently that purports
>|> to deal with the current definition of the C language makes the following
>|> statement: "In C, the proper method is to declare that malloc returns a
>|> pointer to void, then _explicitly_ [emphasis added] coerce the pointer
>|> into the desired type with a cast."
>

>I have made no attempt to look this up, and am assuming that the above is a
>full and complete representation of the statements made there.
>
>There are times even the best of books come up with examples and advice which
>is difficult to defend.

K&R2 says on page 167:

"The pointer returned by malloc or calloc has the proper alignment for the

object in question, but it must be cast into the appropriate type."

This is quire clearly a false statement w.r.t. the ANSI standard. However
I have the draft-ANSI version of K&R2 - perhaps it was corrected in the
later revision?

--
-----------------------------------------
Lawrence Kirby | fr...@genesis.demon.co.uk
Wilts, England | 7073...@compuserve.com
-----------------------------------------

John Bickers

unread,
Aug 16, 1995, 3:00:00 AM8/16/95
to
Quoted from <bnelsonD...@netcom.com> by bne...@netcom.com (Bob Nelson):

[Significance of previous text eluded]

> As of Saturday, 12 August 1995, I've come to believe that this book must
> be in error since you state that the "value returned by malloc shouldn't

There are pros and cons to both schemes. If you cast you have the
advantage of knowing, when you read the line, exactly what sort of
thing is being allocated. The same effect can be achieved with a
comment or using sizeof() in the malloc() argument. Your code will
also be, on the balance of things, more portable to some older
compilers. On the other hand, if you cast, failed to set up a
prototype for malloc(), and your system's ints don't translate
well to pointers, then you may have a problem.

If your code is even reasonably OK then the chance of failure due
to casting malloc() is zero. So both schemes teeter back and forth
in popularity. You'd have to be a bit of an ass to formulate a
strict rule about either approach, but so it goes.

> Bob Nelson: Dallas, Texas, U.S.A. - bne...@netcom.com

--
*** Count Templar, ELITE (FM-287) jbic...@templar.actrix.gen.nz ***
*** All Blacks take Bledisloe Cup 34-23 ***

Derick J.R. Qua-Gonzalez

unread,
Aug 16, 1995, 3:00:00 AM8/16/95
to
bne...@netcom.com (Bob Nelson) writes:

>On Sat, 12 Aug 1995, Dan Pop (Dan...@mail.cern.ch) wrote:

>> 1). malloc returns a void *, period.
>>
>> 2). The value returned by malloc shouldn't be cast. A void pointer is
>> automatically converted by the compiler to any other kind of object
>> pointer.

>Mr. Pop, sir, a book that I like to refer to frequently that purports


>to deal with the current definition of the C language makes the following
>statement: "In C, the proper method is to declare that malloc returns a
>pointer to void, then _explicitly_ [emphasis added] coerce the pointer
>into the desired type with a cast."

Damn, the setup for this quote is more obtuse than a specification for
MIL-SPEC widgets! K&R is making a style suggestion here, not a language
rule.

>I believe the authors of the rather slim book, in contrast to your
>impressive CERN/Geneva credentials, were just employees for some phone
>outfit in a little New Jersey town. These guys at least had the good
>sense to agree with you about <stdlib.h> so maybe the book has *some*
>redeeming qualities.

In ANSI/ISO C, the generic pointer is (void*). The usual conversions
between (void*) and any T* is automatically done. Specifically,
(void*) and a pointer to any object T (as well as 0) are assignment
compatible.

It is _typical_ for the return value of malloc to be cast into the
appropriate type. However, in ISO C, the cast is unnecessary because
malloc returns a (void*).

As much as I love K&R, the definition of C is ISO 9899:1990 with the
Amendment and Technical Corrigendum, and _not_ K&R.

Regards,

Bob Nelson

unread,
Aug 16, 1995, 3:00:00 AM8/16/95
to
On Tue, 15 Aug 1995 19:02:32 GMT, Dan Pop (Dan...@mail.cern.ch) wrote:

>> ...I didn't miss an article posted by Greg Black on 28 March 1995 in
>> a thread debating whether the value returned by malloc should be cast


>> (somebody used K&R2 against my arguments). Here's the relevant part:

>> # To save anybody from the embarrassment of leaping needlessly to the
>> # defence of K&R-2, I asked Dennis Ritchie for an opinion that I could
>> # quote on the validity of the sentence cited above from page 142. He
>> # replied:
>> #
>> # In any case, now that I reread the stuff on p. 142, I think it's
>> # wrong; it's written in such a way that it's not just defensive
>> # against earlier rules, it misrepresents the ANSI rules.

Did Ritchie (and/or Kernighan) likewise go on to explicitly recant
the similiar statement on p. 167 in 7.8.5? Was it felt that his single
admission of misrepresentation was a sufficient "blanket" for that
instance, too?

Is/was there is a third edition of K&R planned/considered to correct
that which is wrong in the current volume?

--
=============================================================================


Bob Nelson: Dallas, Texas, U.S.A. - bne...@netcom.com

Bob Nelson

unread,
Aug 16, 1995, 3:00:00 AM8/16/95
to
On Tue, 15 Aug 1995, Steve Summit (s...@eskimo.com) wrote:

[discussion of K&R's treatment of casting malloc omitted to arrive at
a new point of inquiry]:

>> ...The authors of that book [K&R II] as you might imagine, are


>> somewhat biased towards pre-ANSI, K&R compilers.

Though this may be not worthy of inclusion in your forthcoming FAQ
list and/or book -- I have long found a comment in the "Reference
Manual" of K&R2 (p. 218) to be somewhat intriguing...if not frequent.

Might that bias you refer to be a plausible explanations for their
judgment of "void as an explicit marker of new-style functions
without parameters" as an example of "syntactic ugliness".

Tanmoy Bhattacharya

unread,
Aug 16, 1995, 3:00:00 AM8/16/95
to
In article <bnelsonD...@netcom.com>, bne...@netcom.com (Bob Nelson)
writes:
|> On Tue, 15 Aug 1995, Steve Summit (s...@eskimo.com) wrote:
<snip>

|> >> ...The authors of that book [K&R II] as you might imagine, are
|> >> somewhat biased towards pre-ANSI, K&R compilers.
<snip>

|> Might that bias you refer to be a plausible explanations for their
|> judgment of "void as an explicit marker of new-style functions
|> without parameters" as an example of "syntactic ugliness".

Syntactic ugliness is an altogether different issue. Many people who do not
think that any one in their right mind should cast the return value of
malloc, yet feel `void' is a syntactic ugliness when used to mark absence of
parameters. It was needed only because of `compatibility' with the old
language which had usurped the logical `()' to mean unspecified number of
parameters. (Even within ANSI C, there is argument in favour of this:
parallels with []).

I do not feel that calling (void) a syntactic ugliness is favouring pre-ANSI
compilers.

mj olesen

unread,
Aug 16, 1995, 3:00:00 AM8/16/95
to
The recent discussion about casting or not casting the return value of
malloc() got me wondering about how to properly define a vector of void
pointers.

In the alloc2d() function below, if array is declared as `unsigned char **'
it works fine, but if array is declared as `void **' then the line

array [i] = array [i-1] + rowsize;

generates a compiler complaint that the element size is unknown.

Is there a correct way to define a vector of void pointers, if so -- HOW?

Thanks,

/Mark

/*-------------------------------*-C-*----------------------------------*
* File: array.c
*
* Descript: utility functions for making a generalized 2-D array
*
* Revisions:
* - Jun 94 mjo documented
*----------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>

extern void **alloc2d (size_t elsize, size_t row, size_t col);
extern void free2d (void **array);

/*----------------------------------------------------------------------*
* Function: void **alloc2d (size_t elsize, size_t row, size_t col);
*
* Descript: allocates for array [row][col] in a convenient manner
* - allocates a vector of row pointers
* - allocates (row * col * elsize) of contiguous memory
* - assigns a NULL terminated vector of row pointers
*
* eg, double **mat = (double **) alloc2d (sizeof(double), 2, 2);
*
* Returns: pointer to memory location, NULL on allocation error
*
* Parameters:
* elsize the element size in bytes
* row the number of rows
* col the number of columns
*----------------------------------------------------------------------*/
void **
alloc2d (size_t elsize, size_t row, size_t col)
{
const char msg[] = "alloc2d: alloc error %d\n";
size_t i, rowsize;
#if 0
void ** array; /* doesn't work */
#else
unsigned char ** array; /* works well */
#endif

/* allocate pointers to rows */
array = calloc (row + 1, sizeof(void *)); /* (void **) */
if (array == NULL)
{
fprintf (stderr, msg, 1);
return NULL;
}

rowsize = elsize * col;
/* allocate all rows and set pointers to them */
array [0] = calloc (row, rowsize); /* (void *) */
if (array [0] == NULL)
{
fprintf (stderr, msg, 2);
free (array);
return NULL;
}

for (i = 1; i < row; i++)
array [i] = array [i-1] + rowsize;
array [row] = NULL; /* NULL terminated, safety */

return (void **) array;
}

/*----------------------------------------------------------------------*
* Function: void free2d (void **array);
*
* frees memory of ARRAY which was previously allocated by alloc2d()
*----------------------------------------------------------------------*/
void
free2d (void **array)
{
if (*array) free (*array);
if (array)
{
free (array);
array = NULL;
}
}
/* ---------------------- end-of-file (c source) ---------------------- */


Steve Summit

unread,
Aug 17, 1995, 3:00:00 AM8/17/95
to
In article <bnelsonD...@netcom.com>, bne...@netcom.com
(Bob Nelson) writes:
> On Tue, 15 Aug 1995, Steve Summit (s...@eskimo.com) wrote:
>> ...The authors of that book [K&R II] as you might imagine, are
>> somewhat biased towards pre-ANSI, K&R compilers.
>
> ...I have long found a comment in the "Reference

> Manual" of K&R2 (p. 218) to be somewhat intriguing...if not frequent.
>
> Might that bias you refer to be a plausible explanations for their
> judgment of "void as an explicit marker of new-style functions
> without parameters" as an example of "syntactic ugliness".

I believe that's a different case.

I think that just about everyone agrees that function syntax in
ANSI C -- specifically, the distinction between "old-style" and
"prototyped" declarations and definitions -- is ugly. It's ugly
that you have to use "void" to mark a function that takes 0
arguments; it's ugly that the prototype for

int f(f) float f; { ... }

is

int f(double);

it's ugly that there's two ways of doing everything (except
declaring varargs functions). But the ugliness is unavoidable if
you want to introduce prototypes while preserving compatibility
with existing code.

In any case, K&R2 uses new-style, prototyped function syntax
throughout, so in that respect its authors are less biased
than I am.

Steve Summit
s...@eskimo.com

Glenn Carr

unread,
Aug 17, 1995, 3:00:00 AM8/17/95
to
Sorry about my original error, but I sure have enjoyed (and learned a
bunch from) the verbage it spawned.
--
Glenn Carr, gc...@lgc.com


0 new messages