473,464 Members | 1,720 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

structs and malloc

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(HashNode));

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.
Nov 14 '05 #1
15 2151
begin followup to Lars Tackmann:
what i want, is to ensure that when doing:

HashNode aNode = malloc(sizeof(HashNode)); ^
Something is missing here.
i can be sure of the value of "next" in the aNode
Well, you can use calloc instead of malloc to set all bytes of the
allocated memory to zero. On most platforms that will get you a
null-pointer (and on the one that uses a different representation
you will get a horrible, hard to track runtime error).
[...] can i do this in some easy way or do i need to write my own
memory allocator ???.


Well, you need to do two things:

HashNode* aNode = malloc(sizeof(*aNode));
aNode->next = 0;

If you want to group these two lines into one function, fine with me.

HashNode* new_HashNode(void)
{
HashNode* aNode = malloc(sizeof(*aNode));
aNode->next = 0;
return aNode;
}

--
Für Google, Tux und GPL!
Nov 14 '05 #2
nrk
Alexander Bartolich wrote:
begin followup to Lars Tackmann:
what i want, is to ensure that when doing:

HashNode aNode = malloc(sizeof(HashNode)); ^
Something is missing here.

i can be sure of the value of "next" in the aNode


Well, you can use calloc instead of malloc to set all bytes of the
allocated memory to zero. On most platforms that will get you a
null-pointer (and on the one that uses a different representation
you will get a horrible, hard to track runtime error).
[...] can i do this in some easy way or do i need to write my own
memory allocator ???.


Well, you need to do two things:

HashNode* aNode = malloc(sizeof(*aNode));
aNode->next = 0;

If you want to group these two lines into one function, fine with me.

HashNode* new_HashNode(void)
{
HashNode* aNode = malloc(sizeof(*aNode));
aNode->next = 0;


ITYM:
if ( aNode ) aNode->next = 0;
return aNode;
}


-nrk.
Nov 14 '05 #3
I think that my example was bad - i need a to be able to allocate a entire
array of hash nodes and be sure that all of the nodes has a sane value
from the start.

eg.

HashNode *hashTable = malloc(sizeof(hashNode) * 100);

Thanks

Nov 14 '05 #4
Lars Tackmann wrote:
I think that my example was bad - i need a to be able to allocate a entire
array of hash nodes and be sure that all of the nodes has a sane value
from the start.

eg.

HashNode *hashTable = malloc(sizeof(hashNode) * 100);


I'm confused. If you want an array why do you use a linked list?
Tobias.
Nov 14 '05 #5

"Lars Tackmann" <ro****@diku.dk> wrote in message
i need a to be able to allocate a entire array of hash nodes and be sure
that all of the nodes has a sane value from the start.

eg.

HashNode *hashTable = malloc(sizeof(hashNode) * 100);

malloc() returns a pointer to memory containing garbage. To help makes bugs
more trackable, some implementations set this to a definite bit-pattern,
whilst others don't.

calloc() returns memory set to all bits zero. It is a false friend. On 99%
of systems a pointer with all bits zero is NULL, but there are a few
implementations where this is not true.

What you need to do is to call malloc(), then iterate over the array. For
instance, to create a linked list.

for(i=0;i<99;i++)
hashTable[i].next = &hashtable[i+1];
hashTable[99].next = NULL;
Nov 14 '05 #6
Yep this is what i need - thanks.
On Sun, 21 Dec 2003, Malcolm wrote:

"Lars Tackmann" <ro****@diku.dk> wrote in message
i need a to be able to allocate a entire array of hash nodes and be sure
that all of the nodes has a sane value from the start.

eg.

HashNode *hashTable = malloc(sizeof(hashNode) * 100);

malloc() returns a pointer to memory containing garbage. To help makes bugs
more trackable, some implementations set this to a definite bit-pattern,
whilst others don't.

calloc() returns memory set to all bits zero. It is a false friend. On 99%
of systems a pointer with all bits zero is NULL, but there are a few
implementations where this is not true.

What you need to do is to call malloc(), then iterate over the array. For
instance, to create a linked list.

for(i=0;i<99;i++)
hashTable[i].next = &hashtable[i+1];
hashTable[99].next = NULL;

Nov 14 '05 #7
On Sun, 21 Dec 2003, Tobias Oed wrote:
Lars Tackmann wrote:

I'm confused. If you want an array why do you use a linked list?
Tobias.


In a hash table you usaly have the problem that more than one items hashes
to the same value -. If this happens you link the ones toghter that have
the same hash value (creating a bucket - that you end up searching linary).

That is why i need an array of items that also can be linked to other items.
Nov 14 '05 #8
On Sun, 21 Dec 2003 19:32:18 UTC, Lars Tackmann <ro****@diku.dk>
wrote:
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(HashNode));


change to

if (!(aNode = malloc(sizeof(*aNode)) {
/* as malloc returns a pointer to undetermied memory */
/* initialise the struct members to meaningfull values */
/* to prevent unspezified or in worst case undefined behavior */
aNode->name[0] = 0; /* name is empty */
aNode->hVal = 0ul; /* no value */
aNode->next = NULL /* no pointer assigned */
} else {
/* malloc was unable to give enough memory for a new HashNode */
/* do the needed error handling */
}
--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation

Nov 14 '05 #9

"Lars Tackmann" <ro****@diku.dk> wrote in message
news:Pi******************************@brok.diku.dk ...
On Sun, 21 Dec 2003, Tobias Oed wrote:
Lars Tackmann wrote:

I'm confused. If you want an array why do you use a linked list?
Tobias.
In a hash table you usaly have the problem that more than one items hashes
to the same value -. If this happens you link the ones toghter that have
the same hash value (creating a bucket - that you end up searching

linary).
That is why i need an array of items that also can be linked to other items.

You may have misunderstood how hashtable is usually put together:

horisontally it's an array, vertically items (duplicate hash values/keys)
are
usually implemented as linked list.

See my post in thread "Hash Function". It contains a link to snippets
collection
hashtable implementation - you can take some ideas from there I guess.

with respect,
Toni Uusitalo
Nov 14 '05 #10

horisontally it's an array, vertically items (duplicate hash values/keys)
are
usually implemented as linked list.


sorry, I'm confused myself: of course I meant vertically it's an array,
horisontally items etc.

with respect,
Toni Uusitalo
Nov 14 '05 #11
In article <wmzsGguTDN6N-pn2-JquiV5KfPE2N@moon>,
"The Real OS/2 Guy" <os****@pc-rosenau.de> wrote:
On Sun, 21 Dec 2003 19:32:18 UTC, Lars Tackmann <ro****@diku.dk>
wrote:
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(HashNode));
change to

if (!(aNode = malloc(sizeof(*aNode)) {

Two closing parentheses missing.
/* as malloc returns a pointer to undetermied memory */
/* initialise the struct members to meaningfull values */
/* to prevent unspezified or in worst case undefined behavior */
aNode->name[0] = 0; /* name is empty */
aNode->hVal = 0ul; /* no value */
aNode->next = NULL /* no pointer assigned */
} else {
/* malloc was unable to give enough memory for a new HashNode */
/* do the needed error handling */
}


You just gave a perfect demonstration why experienced programmers write

if ((aNode = malloc(sizeof(*aNode))) != NULL)
Nov 14 '05 #12
Lars Tackmann wrote:

I think that my example was bad - i need a to be able to allocate
a entire array of hash nodes and be sure that all of the nodes
has a sane value from the start.

eg.

HashNode *hashTable = malloc(sizeof(hashNode) * 100);


No, you want to allocate an array of pointers to hash nodes. For
an example, see hashlib.zip, which can be found at:

<http://cbfalconer.home.att.net/download/>

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #13

"Malcolm" <ma*****@55bank.freeserve.co.uk> wrote in message
news:bs**********@news5.svr.pol.co.uk...

"Lars Tackmann" <ro****@diku.dk> wrote in message
i need a to be able to allocate a entire array of hash nodes and be sure
that all of the nodes has a sane value from the start.

eg.

HashNode *hashTable = malloc(sizeof(hashNode) * 100);
malloc() returns a pointer to memory containing garbage. To help makes

bugs more trackable, some implementations set this to a definite bit-pattern,
whilst others don't.

calloc() returns memory set to all bits zero. It is a false friend. On 99%
of systems a pointer with all bits zero is NULL, but there are a few
implementations where this is not true.


calloc() returns a block of memory where each byte of the memory block is
initialised to 0. The pointer returned by calloc() is never set to NULL
unless the function failed to allocate the block. I think you are
confusing the pointer to the memory block with the memory itself here.

Therefore you can use calloc() with 100% confidece that it will work as
described on all systems...

Sean
Nov 14 '05 #14
Sean Kenwrick wrote:
"Malcolm" <ma*****@55bank.freeserve.co.uk> wrote in message
news:bs**********@news5.svr.pol.co.uk...

calloc() returns memory set to all bits zero. It is a false friend. On 99%
of systems a pointer with all bits zero is NULL, but there are a few
implementations where this is not true.
calloc() returns a block of memory where each byte of the memory block is
initialised to 0. The pointer returned by calloc() is never set to NULL
unless the function failed to allocate the block. I think you are
confusing the pointer to the memory block with the memory itself here.


No, he's right. I think you misunderstood his post.

Therefore you can use calloc() with 100% confidece that it will work as
described on all systems...


Sure, it will work as described. But there's no guarantee that the
memory you get back will have a correct, non-trap representation for the
type you intend to use it as. In particular, if you intend to allocate
pointers, the allocated pointers will not be initialized to NULL on some
systems where NULL is not represented with all-bits-zero.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
Nov 14 '05 #15
Lars Tackmann <ro****@diku.dk> wrote in message news:<Pi******************************@brok.diku.d k>...
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(HashNode));

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);
...
}
Nov 14 '05 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
by: Roman Hartmann | last post by:
hello, I do have a question regarding structs. I have a struct (profil) which has a pointer to another struct (point). The struct profil stores the coordinates of points. The problem is that I...
3
by: Christian F | last post by:
Hi, I'm a C-newbie and I would like to know if I am doing something wrong in the code below. It is working, but I'm afraid it might not be correct because I don't really understand everything of...
5
by: Grant Austin | last post by:
What would be the correct syntax for setting up a dynamic array of structs? Suppose you have a struct declared: struct relation { FILE * binFile; unsigned int numAttrs; struct attrList *...
10
by: Patricia Van Hise | last post by:
Is it possible to access a field of a struct which is a field of another struct? Ex. struct subStr{ int num1; int num2; }; struct myStr { int num3; subStr *lock; };
10
by: Kieran Simkin | last post by:
Hi, I wonder if anyone can help me, I've been headscratching for a few hours over this. Basically, I've defined a struct called cache_object: struct cache_object { char hostname; char ipaddr;...
6
by: Matthew Jakeman | last post by:
If i create a cruct like so : struct test{ char *var1 ; int var2 ; short var3 ; } and i want to allocate it memory, should i allocate enough to hold the max amount of data that will go...
5
by: Bidule | last post by:
Hi, I'm trying to sort structs defined as follows: struct combinationRec { float score; char* name; }; The number of structs and the length of the "name" field are not known
15
by: Paminu | last post by:
Still having a few problems with malloc and pointers. I have made a struct. Now I would like to make a pointer an array with 4 pointers to this struct. #include <stdlib.h> #include <stdio.h>...
2
by: hal | last post by:
Hi, I'm trying to make an array of pointers to 'TwoCounts' structs, where the size of the array is arraySize. Right now I'm just mallocing enough space for all the pointers to the structs, and...
8
by: kiser89 | last post by:
I'm having a problem with my array of structs and segmentation faults. I have this struct that represents one line of a source file: struct threeTokens { int lineNumber; char* cmd; char* param;...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.