473,769 Members | 1,618 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question on free() ing a hash table

Excercise 6-5

Write a functon undef that will remove a name and defintion from the
table maintained by lookup and install.

Code:

unsigned hash(char *s);

void undef(char *s)
{
int h;
struct nlist *prev, *np;

prev = NULL;
h = hash(s);
for(np = hashtab[h]; np!=NULL; np = np->next){
if(strcmp(s, np->name) == 0)
break;
prev = np;
}

if(np !=NULL) {
if(prev == NULL)
hashtab[h] = np->next;
else
prev->next = np->next;
free((void *) np->name);
free((void *) np->defn);
free((void *) np);
}
}

The question is, how come I have to free() both np->name and np->defn?
Ie, how come I can't just free() np?

Oct 26 '07 #1
13 5084
Chad wrote:
Excercise 6-5

Write a functon undef that will remove a name and defintion from the
table maintained by lookup and install.

Code:

unsigned hash(char *s);

void undef(char *s)
{
int h;
struct nlist *prev, *np;

prev = NULL;
h = hash(s);
for(np = hashtab[h]; np!=NULL; np = np->next){
if(strcmp(s, np->name) == 0)
break;
prev = np;
}

if(np !=NULL) {
if(prev == NULL)
hashtab[h] = np->next;
else
prev->next = np->next;
free((void *) np->name);
free((void *) np->defn);
free((void *) np);
}
}

The question is, how come I have to free() both np->name and np->defn?
Ie, how come I can't just free() np?
Because memory for them was allocated separately.
You need a call to free() for every call to malloc(). You construct the
struct np with three calls to malloc - one for the struct itself and
two more to initialise it's members 'name' and 'defn' to point to
usable storage. Thus when destroying the struct you need to deallocate
storage pointed to by these members too.

In particular if 'name' and 'defn' are the only pointers that point to
their storage, then you must free() them _before_ calling free() on np,
or else you'll create a memory leak.

Note that the casts to void * within the calls to free() are not needed.

Oct 26 '07 #2
On Oct 25, 7:02 pm, santosh <santosh....@gm ail.comwrote:
Chad wrote:
Excercise 6-5
Write a functon undef that will remove a name and defintion from the
table maintained by lookup and install.
Code:
unsigned hash(char *s);
void undef(char *s)
{
int h;
struct nlist *prev, *np;
prev = NULL;
h = hash(s);
for(np = hashtab[h]; np!=NULL; np = np->next){
if(strcmp(s, np->name) == 0)
break;
prev = np;
}
if(np !=NULL) {
if(prev == NULL)
hashtab[h] = np->next;
else
prev->next = np->next;
free((void *) np->name);
free((void *) np->defn);
free((void *) np);
}
}
The question is, how come I have to free() both np->name and np->defn?
Ie, how come I can't just free() np?

Because memory for them was allocated separately.
You need a call to free() for every call to malloc(). You construct the
struct np with three calls to malloc - one for the struct itself and
two more to initialise it's members 'name' and 'defn' to point to
usable storage. Thus when destroying the struct you need to deallocate
storage pointed to by these members too.

In particular if 'name' and 'defn' are the only pointers that point to
their storage, then you must free() them _before_ calling free() on np,
or else you'll create a memory leak.

Note that the casts to void * within the calls to free() are not needed.

The question was taken from page 145 in the "The C Programming
Langauge" by K & R. I think what is tripping me up when trying to free
the structure is the following line of code on page 145.

In install(), they have the following line of code:

if((np->defn = strdup(defn)) == NULL)
return NULL.

For reasons that still elude me, every time I see this line of code, I
keep thinking that memory ISN'T allocated for np->defn.

Oct 26 '07 #3
On Oct 25, 7:02 pm, santosh <santosh....@gm ail.comwrote:
Chad wrote:
Excercise 6-5
Write a functon undef that will remove a name and defintion from the
table maintained by lookup and install.
Code:
unsigned hash(char *s);
void undef(char *s)
{
int h;
struct nlist *prev, *np;
prev = NULL;
h = hash(s);
for(np = hashtab[h]; np!=NULL; np = np->next){
if(strcmp(s, np->name) == 0)
break;
prev = np;
}
if(np !=NULL) {
if(prev == NULL)
hashtab[h] = np->next;
else
prev->next = np->next;
free((void *) np->name);
free((void *) np->defn);
free((void *) np);
}
}
The question is, how come I have to free() both np->name and np->defn?
Ie, how come I can't just free() np?

Because memory for them was allocated separately.
You need a call to free() for every call to malloc(). You construct the
struct np with three calls to malloc - one for the struct itself and
two more to initialise it's members 'name' and 'defn' to point to
usable storage. Thus when destroying the struct you need to deallocate
storage pointed to by these members too.

In particular if 'name' and 'defn' are the only pointers that point to
their storage, then you must free() them _before_ calling free() on np,
or else you'll create a memory leak.

Note that the casts to void * within the calls to free() are not needed.

The question was taken from page 145 in the "The C Programming
Langauge" by K & R (Second Edition). I think what is tripping me up
when trying to free the structure is the following line of code on
page 145.

In install(), they have the following line of code:

if((np->defn = strdup(defn)) == NULL)
return NULL;

For reasons that still elude me, every time I see this line of code, I
keep thinking that memory ISN'T allocated for np->defn.

Oct 26 '07 #4
Chad wrote:
On Oct 25, 7:02 pm, santosh <santosh....@gm ail.comwrote:
>Chad wrote:
Excercise 6-5
Write a functon undef that will remove a name and defintion from
the table maintained by lookup and install.
Code:
unsigned hash(char *s);
void undef(char *s)
{
int h;
struct nlist *prev, *np;
prev = NULL;
h = hash(s);
for(np = hashtab[h]; np!=NULL; np = np->next){
if(strcmp(s, np->name) == 0)
break;
prev = np;
}
if(np !=NULL) {
if(prev == NULL)
hashtab[h] = np->next;
else
prev->next = np->next;
free((void *) np->name);
free((void *) np->defn);
free((void *) np);
}
}
The question is, how come I have to free() both np->name and
np->defn? Ie, how come I can't just free() np?

Because memory for them was allocated separately.
You need a call to free() for every call to malloc(). You construct
the struct np with three calls to malloc - one for the struct itself
and two more to initialise it's members 'name' and 'defn' to point to
usable storage. Thus when destroying the struct you need to
deallocate storage pointed to by these members too.

In particular if 'name' and 'defn' are the only pointers that point
to their storage, then you must free() them _before_ calling free()
on np, or else you'll create a memory leak.

Note that the casts to void * within the calls to free() are not
needed.


The question was taken from page 145 in the "The C Programming
Langauge" by K & R (Second Edition). I think what is tripping me up
when trying to free the structure is the following line of code on
page 145.

In install(), they have the following line of code:

if((np->defn = strdup(defn)) == NULL)
return NULL;

For reasons that still elude me, every time I see this line of code, I
keep thinking that memory ISN'T allocated for np->defn.
This line attempts to duplicate the string pointed to by 'defn' passed
to strdup() at 'np-defn.' If strdup() fails it returns NULL. Otherwise
you have to explicitly free() memory allocated by it.

Note that strdup() is not defined by ISO C, though it's a common
extension.

See man strdup on UNIX systems.

Oct 26 '07 #5
santosh wrote:
>
Chad wrote:
On Oct 25, 7:02 pm, santosh <santosh....@gm ail.comwrote:
Chad wrote:
Excercise 6-5

Write a functon undef that will remove a name and defintion from
the table maintained by lookup and install.

Code:

unsigned hash(char *s);

void undef(char *s)
{
int h;
struct nlist *prev, *np;

prev = NULL;
h = hash(s);
for(np = hashtab[h]; np!=NULL; np = np->next){
if(strcmp(s, np->name) == 0)
break;
prev = np;
}

if(np !=NULL) {
if(prev == NULL)
hashtab[h] = np->next;
else
prev->next = np->next;
free((void *) np->name);
free((void *) np->defn);
free((void *) np);
}
}

The question is, how come I have to free() both np->name and
np->defn? Ie, how come I can't just free() np?

Because memory for them was allocated separately.
You need a call to free() for every call to malloc(). You construct
the struct np with three calls to malloc
- one for the struct itself
and two more to initialise it's members 'name'
and 'defn' to point to
usable storage. Thus when destroying the struct you need to
deallocate storage pointed to by these members too.

In particular if 'name' and 'defn' are the only pointers that point
to their storage, then you must free() them _before_ calling free()
on np, or else you'll create a memory leak.

Note that the casts to void * within the calls to free() are not
needed.

The question was taken from page 145 in the "The C Programming
Langauge" by K & R (Second Edition). I think what is tripping me up
when trying to free the structure is the following line of code on
page 145.

In install(), they have the following line of code:

if((np->defn = strdup(defn)) == NULL)
return NULL;

For reasons that still elude me,
every time I see this line of code, I
keep thinking that memory ISN'T allocated for np->defn.

This line attempts to duplicate the string pointed to by 'defn' passed
to strdup() at 'np-defn.' If strdup() fails it returns NULL. Otherwise
you have to explicitly free() memory allocated by it.

Note that strdup() is not defined by ISO C, though it's a common
extension.

See man strdup on UNIX systems.
strdup is defined on page 143 of K&R2.

--
pete
Oct 26 '07 #6
On Oct 26, 8:50 am, pete <pfil...@mindsp ring.comwrote:
>
strdup is defined on page 143 of K&R2.
K&R2 is old.
Oct 26 '07 #7
vi************* ***@gmail.com wrote:
On Oct 26, 8:50 am, pete <pfil...@mindsp ring.comwrote:

strdup is defined on page 143 of K&R2.

K&R2 is old.
True, but irrelevant. strdup() is normally considered a Unixoid function
here (and with reason), but in the context of the OP's problem, it is
allowed, simply because that problem itself is from K&R, and presumes
the existence of K&R's, just a little earlier defined, strdup(), not
POSIX's one.

Richard
Oct 26 '07 #8
vi************* ***@gmail.com wrote:
On Oct 26, 8:50 am, pete <pfil...@mindsp ring.comwrote:
>>
strdup is defined on page 143 of K&R2.

K&R2 is old.
It's age is irrelevant to the problem at hand. As pete says strdup is
defined elsewhere in the book.

I think that Chad's confusion stems from the fact that he believes 'np'
may be uninitialised. It is however initialised by the function lookup.

Oct 26 '07 #9
On 26 Oct, 03:29, Chad <cdal...@gmail. comwrote:
In install(), they have the following line of code:

if((np->defn = strdup(defn)) == NULL)
return NULL;

For reasons that still elude me, every time I see this line of code, I
keep thinking that memory ISN'T allocated for np->defn.
Perhaps you could try rewriting it as:

np->defn = strdup(defn);
if(np->defn == NULL) return NULL;

Readability is important, and this version is only a smidgeon less
efficient.

Paul.

Oct 27 '07 #10

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

Similar topics

8
3271
by: Együd Csaba | last post by:
Hi All, how can I improve the query performance in the following situation: I have a big (4.5+ million rows) table. One query takes approx. 9 sec to finish resulting ~10000 rows. But if I run simultaneously 4 similar queries it takes nearly 5 minutes instead of 4 times 9 seconds or something near of that. here is a sample query: select mertido, fomeazon, ertektipus, mertertek from t_me30 where fomeazon in (select distinct fomeazon...
23
2750
by: Serve La | last post by:
When I write a medium to large sized C application I tend to create structures first, then makeStruct and freeStruct functions that dynamically allocate/free the struct and then I create a bunch of functions that operate on the struct. Example: typedef struct ccHashTab { ..... } ccHashTab;
7
1706
by: J L | last post by:
I have defined a structure private structure FieldInfo dim FieldName as string dim OrdinalPostioin as Integer dim DataType as Type dim Size as Integer end structure I read this information from a DataReader which retrieves schema info
2
1383
by: Terrance | last post by:
Hello, I have a question in regards to hashtables that I was hoping someone can share some light on. I'm currently working with VB.net and I'm trying to learn as much as possible about the developer software. Can someone clarify what a hashtable is? What is it's purpose? Why/when should one be used? After doing some reading I kind of understand it's like an array but what makes it so different from any other type of array that a...
8
3116
by: Rakesh | last post by:
Hi - What is wrong this implementation? I get a core dump at the free() statement? Thanks Rakesh #include <ext/hash_map> #include <iostream.h> #include <ext/hash_set>
18
2866
by: Nobody | last post by:
I've been looking for a job for a while now, and have run into this interview question twice now... and have stupidly kind of blown it twice... (although I've gotten better)... time to finally figure this thing out... basically the interview question is: given an unsorted listed such as: 3,1,3,7,1,2,4,4,3 find the FIRST UNIQUE number, in this case 7... and of course the list can be millions long...
11
2711
by: merrittr | last post by:
Hi in the code below in the main the hash table from K&R example replaces a node when a collision occurs What I am trying to do is set it up to "chain" another structure beside the node that it collides with can you spot what I am doing wrong? zork and 122 are to 2 that collide so the "zork" node gets overwritten by 121.
1
1251
by: Anonymous | last post by:
I am writing a template HashTable class. I have got it working, but I want to make the code more generic and more robust. The current code looks something like this: template <class InnerType, class KeyType, class KeyToSizeT> class myHash { // Impl here };
2
390
by: Paul Hsieh | last post by:
On Nov 4, 12:24 pm, c...@tiac.net (Richard Harter) wrote: This is the whole idea behind "opaque handles". The problem is that you need to allow for the possibility of live handles and obsolete handles having a mixed existence during the lifetime of your program. That being said, there is a typical "good enough for the real world" solution that you can implement in pure C. You need a central "bobble object management interface". The...
0
9589
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...
1
9994
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9863
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
8870
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
7408
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
5298
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
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3561
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.