473,782 Members | 2,494 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
13 5086
Chad wrote:
>
.... snip ...
>
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.
Why? The dependency is obviously on strdup, and the return of NULL
presumably means that it failed. (strdup is non-standard.)
Therefore passing this test means it succeeded.

A better form IMO would be:

if (np->defn = strdup(defn)) return NULL;
else {
/* whatever is required */
}

and you can omit the else if you wish. But this form is clearer in
the middle of a function, while the omitted else is better used at
the start of the function.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>

--
Posted via a free Usenet account from http://www.teranews.com

Oct 27 '07 #11
"CBFalconer " <cb********@yah oo.coma écrit dans le message de news:
47************* **@yahoo.com...
Chad wrote:
>>
... snip ...
>>
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.

Why? The dependency is obviously on strdup, and the return of NULL
presumably means that it failed. (strdup is non-standard.)
Therefore passing this test means it succeeded.

A better form IMO would be:

if (np->defn = strdup(defn)) return NULL;
else {
/* whatever is required */
}
Ugly style:
- assignment as a test expression: a classic cause of stupid bugs.
- if and then clauses on the same line.
- no symmetry between then and else clause.
and you can omit the else if you wish. But this form is clearer in
the middle of a function, while the omitted else is better used at
the start of the function.
Actually, direct return of NULL at the start of the function is better
without an else clause and is OK because it is easy to assert correctness.
This form would be quite error prone in the middle of a large function,
where returning NULL without proper cleanup of locally allocated memory
and/or acquired ressources would go unnoticed precisely because the return
statement does not stand out on its own. Definitely avoid this style.

--
Chqrlie.
Oct 27 '07 #12
santosh wrote:
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.
Your emphasis on before makes it look like the alternative is after (as
opposed to "not at all"). Doing that would be an undefined behaviour,
not just a memory leak.
Oct 28 '07 #13
On 27 Oct, 16:17, CBFalconer <cbfalco...@yah oo.comwrote:
Chad wrote:

... snip ...
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.

Why? The dependency is obviously on strdup, and the return of NULL
presumably means that it failed. (strdup is non-standard.)
Therefore passing this test means it succeeded.

A better form IMO would be:

if (np->defn = strdup(defn)) return NULL;
else {
/* whatever is required */
}
Correct me if I'm wrong, but doesn't your version do the opposite of
the original one?

Nov 8 '07 #14

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
2752
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
3117
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
2867
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
1252
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
9639
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
9479
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10311
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...
1
10080
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
8967
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
7492
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
6733
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
5378
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...
3
2874
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.