473,832 Members | 2,292 Online
Bytes | Software Development & Data Engineering Community
+ 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(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.
Nov 14 '05
15 2189

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@mo on>,
"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(H ashNode));
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(h ashNode) * 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********@yah oo.com) (cb********@wor ldnet.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.u k> wrote in message
news:bs******** **@news5.svr.po l.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(h ashNode) * 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.u k> wrote in message
news:bs******** **@news5.svr.po l.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
implementatio ns 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.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);
...
}
Nov 14 '05 #16

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

Similar topics

11
3408
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 don't know how many points there will be in every struct in the end, so I have to allocate memory dynamically for them and can't use an array of fixed size, unfortunately. I would like to know if there is a better way to access struct members...
3
2175
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 it. There are lots of pointers and pointers to pointers which makes me confused. First my typedef: typedef struct { double re;
5
2073
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 * relAttrs; /* definition shown at end of post */ };
10
1996
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
4136
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
325
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 into the char * plus the size of an int plus the
5
2769
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
3843
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> typedef struct _tnode_t { void *content; struct _tnode_t *kids;
2
11945
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 mallocing space for the pointer 'countPtr' in each struct, but do I need to do anything else? Thanks. typedef struct TwoCounts { int *countPtr;
8
3222
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; }; line; This is the code that tries to fill the array of structs, which is a global variable called program: program = malloc(numLines * sizeof(line)); while(NULL != fgets(buffer, SIZE, fp)){ tokenPtr = strtok(buffer,"...
0
9794
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10780
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10212
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9319
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7753
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6951
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5623
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5788
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4420
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.