473,399 Members | 3,038 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

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 5048
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....@gmail.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....@gmail.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....@gmail.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....@gmail.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...@mindspring.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...@mindspring.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...@mindspring.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
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********@yahoo.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...@yahoo.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
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...
23
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...
7
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...
2
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...
8
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
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...
11
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...
1
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,...
2
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...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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,...
0
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...
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...
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,...

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.