As dirkgently said, don't case the return of malloc()
in C, doing so is useless and can hide errors.
Also, to compute the address following the Node header, I find it cleaner to do it like this:
t->data = t + 1;
This works because t
is a typed pointer, so arithmetic on it works fine. Adding one increments it by the size of the pointed-to data, i.e. sizeof (Node)
in this case. I find this usage idiomatic for this particular case, of computing the address immediately following something just malloc()
ed (when that "something" is a well-defined type with a statically known size, as the Node
struct in this case, of course).
This has the following benefits:
- No repetition of the type name.
- No
sizeof
, so shorter.
- Again, no cast.
- Very simple arithmetic involved, easy to read.
I realized there's an error with your use of the Node
type before it's properly declared, too. I don't agree with dirkgently's solution, here's how it should look, in C:
/* This introduces the type name "Node", as an alias for an undefined struct. */
typedef struct Node Node;
struct Node {
Node *next; /* This is OK, the compiler only needs to know size of pointer. */
void *data;
};
For completeness, and since I never tire of showing how I consider code like this should be written, here's an example of a function to create a new node to hold n bytes of data:
Node * node_new(size_t n)
{
Node *node;
if((node = malloc(sizeof *node + n)) != NULL)
{
node->next = NULL;
node->data = node + 1;
}
return node;
}
That's it. Note use of sizeof
on the pointer target in the malloc()
call, to avoid repeating the type name and making an easy-to-forget dependency if the type should ever change.