Lars Tackmann <ro****@diku.dk > wrote in message news:<Pi******* *************** ********@brok.d iku.dk>...
Hi, i have the following type and struct defined
typedef struct hNode {
unsigned char name[1024];
unsigned long hVal;
struct hNode *next;
} HashNode;
what i want, is to ensure that when doing:
HashNode aNode = malloc(sizeof(H ashNode));
i can be sure of the value of "next" in the aNode (eg. later in the
program i want to compare the value of "next" in aNode to see if it has
been linked to another HashNode) --- can i do this in
some easy way or do i need to write my own memory allocator ???.
Thanks.
If you're relying members of your struct to be initialized to a known
value, you're best off writing your own allocator function. Heck, for
dynamically allocating *any* abstract data type, you're best off
writing your own allocator function.
HashNode *newHashNode (char *name, long hval)
{
HashNode *tmp;
tmp = malloc (sizeof *tmp);
if (tmp)
{
tmp->next = NULL;
tmp->hval = hval;
if (name)
{
if (strlen (name) < sizeof tmp->name)
strcpy (tmp->name, name);
else
{
/*
** Input name is too long to store in data type.
** Several ways to deal with this:
** 1. Report an error, abort the operation (free tmp)
** 2. Report an error, continue operation but
** don't store name
** 3. Report an error, store truncated name
**
** This code reports an error and attempts to
** store a truncated name.
*/
my_log_error (DATA_ERROR, NAME_TOO_LONG);
strncpy (tmp->name, sizeof tmp->name, name);
tmp->name[sizeof tmp->name - 1] = 0;
}
}
else
{
/* no name passed, initialize name buffer to 0 */
memset (tmp->name, 0, sizeof tmp->name);
}
}
else
{
/* report memory allocation error */
my_log_error (SYSTEM_ERROR, MALLOC_FAILED);
}
return tmp;
}
int main (void)
{
HashNode *node = newHashNode ("test", 0);
...
}