Re: Linked List Library
- From: Ben Pfaff <blp@xxxxxxxxxxxxxxx>
- Date: Thu, 20 Sep 2007 20:49:16 -0700
TBass <tbj@xxxxxxxxxxxxxxxxxxx> writes:
When I malloc the structure, I use
the following statement:
pNewNode = (ADCLIST *)malloc( sizeof( ADCLIST ) );
I don't recommend casting the return value of malloc():
* The cast is not required in ANSI C.
* Casting its return value can mask a failure to #include
<stdlib.h>, which leads to undefined behavior.
* If you cast to the wrong type by accident, odd failures can
result.
In unusual circumstances it may make sense to cast the return value of
malloc(). P. J. Plauger, for example, has good reasons to want his
code to compile as both C and C++, and C++ requires the cast, as he
explained in article <9sFIb.9066$nK2.4505@xxxxxxxxxxxxxxxxxxxx>.
However, Plauger's case is rare indeed. Most programmers should write
their code as either C or C++, not in the intersection of the two.
When calling malloc(), I recommend using the sizeof operator on
the object you are allocating, not on the type. For instance,
*don't* write this:
int *x = malloc (128 * sizeof (int)); /* Don't do this! */
Instead, write it this way:
int *x = malloc (128 * sizeof *x);
There's a few reasons to do it this way:
* If you ever change the type that `x' points to, it's not
necessary to change the malloc() call as well.
This is more of a problem in a large program, but it's still
convenient in a small one.
* Taking the size of an object makes writing the statement
less error-prone. You can verify that the sizeof syntax is
correct without having to look at the declaration.
Where:
typedef struct ADCLIST_el
{
struct ADCLIST_el *pPrev;
struct ADCLIST_el *pNext;
void *pData;
} ADCLIST_el;
typedef ADCLIST_el ADCLIST;
That's two more 'typedef's than you really need. I rarely see
more than one for any given structure. I personally don't use
any at all for structures, in ordinary circumstances.
Is that the proper way to get the size of memory that the structure
will contain?
It's OK, but not the way that I would write it.
--
char a[]="\n .CJacehknorstu";int putchar(int);int main(void){unsigned long b[]
={0x67dffdff,0x9aa9aa6a,0xa77ffda9,0x7da6aa6a,0xa67f6aaa,0xaa9aa9f6,0x11f6},*p
=b,i=24;for(;p+=!*p;*p/=4)switch(0[p]&3)case 0:{return 0;for(p--;i--;i--)case+
2:{i++;if(i)break;else default:continue;if(0)case 1:putchar(a[i&15]);break;}}}
.
- Follow-Ups:
- Re: Linked List Library
- From: Roland Pibinger
- Re: Linked List Library
- From: TBass
- Re: Linked List Library
- References:
- Linked List Library
- From: TBass
- Re: Linked List Library
- From: Ben Pfaff
- Re: Linked List Library
- From: TBass
- Re: Linked List Library
- From: Ben Pfaff
- Re: Linked List Library
- From: TBass
- Linked List Library
- Prev by Date: Re: Linked List Library
- Next by Date: Re: Struct size
- Previous by thread: Re: Linked List Library
- Next by thread: Re: Linked List Library
- Index(es):
Relevant Pages
|