473,839 Members | 1,411 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Does malloc() reuse addresses?

Hi all,

my question is:

if i allocate some memory with malloc() and later free it (using
free()), is there a possibility that a consequent malloc() will
allocate memort at the same starting address and will return the same
pointer as the previous malloc(). I would like to have confirmation on
whether this is practically a concern when pointers are used to
uniquely identify data structure instances - like in this example:

int isInstanceValid (myStrict* inst)
{
int i;
for (i=0; i<instCount; ++i)
if (instances[i] == inst)
return 1;

return 0;
}

In this example, if an instance is freed, and a pointer to it becomes
non-valid, and later a new structure is allocated in the list, the
function will return that the pointer is valid, although it is actually
not the instance that was originally referred.

Jul 14 '06
48 5863

avasilev wrote:
Hi all,

my question is:

if i allocate some memory with malloc() and later free it (using
free()), is there a possibility that a consequent malloc() will
allocate memort at the same starting address and will return the same
pointer as the previous malloc(). I would like to have confirmation on
whether this is practically a concern when pointers are used to
uniquely identify data structure instances - like in this example:

int isInstanceValid (myStrict* inst)
{
int i;
for (i=0; i<instCount; ++i)
if (instances[i] == inst)
return 1;

return 0;
}

In this example, if an instance is freed, and a pointer to it becomes
non-valid, and later a new structure is allocated in the list, the
function will return that the pointer is valid, although it is actually
not the instance that was originally referred.


Ok I will clarify this a bit, sice some people did not get it properly.
I have a list of instance pointers. Every allocated instance is added
to this list and every freed instance is immediately removed from
there. The problem is that copies of these pointers need to be passed
around, and it may happen that when such a copy has to be used, the
instance it points to may be already gone. So a way to validate the
pointer is needed - and this pointer comparison approach was chosen -
not by me, I am kindof revising the thing. So my question was to
confirm how reliable is the current verification mechanism. My opinion
is that it is not, since pointer values for different instances (in
time) may conicide.

Jul 14 '06 #11
"avasilev" <al********@gma il.comwrote in message
news:11******** **************@ m79g2000cwm.goo glegroups.com.. .
>
avasilev wrote:
>Hi all,

my question is:

if i allocate some memory with malloc() and later free it (using
free()), is there a possibility that a consequent malloc() will
allocate memort at the same starting address and will return the same
pointer as the previous malloc(). I would like to have confirmation on
whether this is practically a concern when pointers are used to
uniquely identify data structure instances - like in this example:

int isInstanceValid (myStrict* inst)
{
int i;
for (i=0; i<instCount; ++i)
if (instances[i] == inst)
return 1;

return 0;
}

In this example, if an instance is freed, and a pointer to it becomes
non-valid, and later a new structure is allocated in the list, the
function will return that the pointer is valid, although it is actually
not the instance that was originally referred.

Ok I will clarify this a bit, sice some people did not get it properly.
I have a list of instance pointers. Every allocated instance is added
to this list and every freed instance is immediately removed from
there. The problem is that copies of these pointers need to be passed
around, and it may happen that when such a copy has to be used, the
instance it points to may be already gone. So a way to validate the
pointer is needed - and this pointer comparison approach was chosen -
not by me, I am kindof revising the thing. So my question was to
confirm how reliable is the current verification mechanism. My opinion
is that it is not, since pointer values for different instances (in
time) may conicide.
If you know for sure that:
1. The pointers in your list are valid pointers (all the bad ones, having
been removed)
2. The pointers in your list point to the appropriate data type

You still have a problem.

Suppose that pointer 0xdeadbeef is some valid "bucket of chicken" pointer in
your list. You assign that pointer to some struct in memory and say,
"Here's your bucket of chicken."
Later on, the pointer 0xdeadbeef gets freed. Now, we have this pointer,
0xdeadbeef and we want to know if it is valid. If we examine our "bucket of
chicken" pointer and say:
pointer 0 in the list is 0xc0ffc0ff. Is pointer 0xc0ffc0ff equal to pointer
0xdeadbeef?

The simple act of examining the contents of the pointer that is storing
0xdeadbeef invokes undefined behavior. Your computer could dump core, or
Scott Nudds could come flying out of your left nostril. Really, it's
practically in the standard. At least comp.std.c made a similar remark
concerning demons some time ago.

Jul 14 '06 #12

Dann Corbit wrote:
"avasilev" <al********@gma il.comwrote in message
news:11******** **************@ m79g2000cwm.goo glegroups.com.. .

avasilev wrote:
Hi all,

my question is:

if i allocate some memory with malloc() and later free it (using
free()), is there a possibility that a consequent malloc() will
allocate memort at the same starting address and will return the same
pointer as the previous malloc(). I would like to have confirmation on
whether this is practically a concern when pointers are used to
uniquely identify data structure instances - like in this example:

int isInstanceValid (myStrict* inst)
{
int i;
for (i=0; i<instCount; ++i)
if (instances[i] == inst)
return 1;

return 0;
}

In this example, if an instance is freed, and a pointer to it becomes
non-valid, and later a new structure is allocated in the list, the
function will return that the pointer is valid, although it is actually
not the instance that was originally referred.
Ok I will clarify this a bit, sice some people did not get it properly.
I have a list of instance pointers. Every allocated instance is added
to this list and every freed instance is immediately removed from
there. The problem is that copies of these pointers need to be passed
around, and it may happen that when such a copy has to be used, the
instance it points to may be already gone. So a way to validate the
pointer is needed - and this pointer comparison approach was chosen -
not by me, I am kindof revising the thing. So my question was to
confirm how reliable is the current verification mechanism. My opinion
is that it is not, since pointer values for different instances (in
time) may conicide.

If you know for sure that:
1. The pointers in your list are valid pointers (all the bad ones, having
been removed)
2. The pointers in your list point to the appropriate data type

You still have a problem.
No no, Im no examining the moemory that hte pointer points to, I am
simply comparing the values of the pointers themselves, i.e. I am
comparing the addresses, not the contents of the memory that is pointed
to.
Suppose that pointer 0xdeadbeef is some valid "bucket of chicken" pointer in
your list. You assign that pointer to some struct in memory and say,
"Here's your bucket of chicken."
Later on, the pointer 0xdeadbeef gets freed. Now, we have this pointer,
0xdeadbeef and we want to know if it is valid. If we examine our "bucket of
chicken" pointer and say:
pointer 0 in the list is 0xc0ffc0ff. Is pointer 0xc0ffc0ff equal to pointer
0xdeadbeef?

The simple act of examining the contents of the pointer that is storing
0xdeadbeef invokes undefined behavior. Your computer could dump core, or
Scott Nudds could come flying out of your left nostril. Really, it's
practically in the standard. At least comp.std.c made a similar remark
concerning demons some time ago.
Jul 14 '06 #13

Dann Corbit wrote:
"avasilev" <al********@gma il.comwrote in message
news:11******** **************@ m79g2000cwm.goo glegroups.com.. .

avasilev wrote:
Hi all,

my question is:

if i allocate some memory with malloc() and later free it (using
free()), is there a possibility that a consequent malloc() will
allocate memort at the same starting address and will return the same
pointer as the previous malloc(). I would like to have confirmation on
whether this is practically a concern when pointers are used to
uniquely identify data structure instances - like in this example:

int isInstanceValid (myStrict* inst)
{
int i;
for (i=0; i<instCount; ++i)
if (instances[i] == inst)
return 1;

return 0;
}

In this example, if an instance is freed, and a pointer to it becomes
non-valid, and later a new structure is allocated in the list, the
function will return that the pointer is valid, although it is actually
not the instance that was originally referred.
Ok I will clarify this a bit, sice some people did not get it properly.
I have a list of instance pointers. Every allocated instance is added
to this list and every freed instance is immediately removed from
there. The problem is that copies of these pointers need to be passed
around, and it may happen that when such a copy has to be used, the
instance it points to may be already gone. So a way to validate the
pointer is needed - and this pointer comparison approach was chosen -
not by me, I am kindof revising the thing. So my question was to
confirm how reliable is the current verification mechanism. My opinion
is that it is not, since pointer values for different instances (in
time) may conicide.

If you know for sure that:
1. The pointers in your list are valid pointers (all the bad ones, having
been removed)
2. The pointers in your list point to the appropriate data type

You still have a problem.

Suppose that pointer 0xdeadbeef is some valid "bucket of chicken" pointer in
your list. You assign that pointer to some struct in memory and say,
"Here's your bucket of chicken."
Later on, the pointer 0xdeadbeef gets freed. Now, we have this pointer,
0xdeadbeef and we want to know if it is valid. If we examine our "bucket of
chicken" pointer and say:
pointer 0 in the list is 0xc0ffc0ff. Is pointer 0xc0ffc0ff equal to pointer
0xdeadbeef?

The simple act of examining the contents of the pointer that is storing
0xdeadbeef invokes undefined behavior. Your computer could dump core, or
Scott Nudds could come flying out of your left nostril. Really, it's
practically in the standard. At least comp.std.c made a similar remark
concerning demons some time ago.
No no, Im no examining the moemory that hte pointer points to, I am
simply comparing the values of the pointers themselves, i.e. I am
comparing the addresses, not the contents of the memory that is pointed
to.

Jul 14 '06 #14
"avasilev" <al********@gma il.comwrites:
Dann Corbit wrote:
[...]
>The simple act of examining the contents of the pointer that is storing
0xdeadbeef invokes undefined behavior. Your computer could dump core, or
Scott Nudds could come flying out of your left nostril. Really, it's
practically in the standard. At least comp.std.c made a similar remark
concerning demons some time ago.

No no, Im no examining the moemory that hte pointer points to, I am
simply comparing the values of the pointers themselves, i.e. I am
comparing the addresses, not the contents of the memory that is pointed
to.
Understood, but just examining the pointer value itself, without
dereferencing it, invokes undefined behavior.

Concretely:

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
void *ptr;
ptr = malloc(42);
printf("ptr = %p\n", ptr);
free(ptr);
printf("ptr = %p\n", ptr);
return 0;
}

The second printf call invokes UB (assuming the malloc() succeeded).

In real life, this is unlikely to cause any problems, but strictly
speaking a pointer to an object becomes indeterminate when the object
reaches the end of its lifetime.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jul 14 '06 #15
avasilev wrote:
[...]
Ok I will clarify this a bit, sice some people did not get it properly.
I have a list of instance pointers. Every allocated instance is added
to this list and every freed instance is immediately removed from
there. The problem is that copies of these pointers need to be passed
around, and it may happen that when such a copy has to be used, the
instance it points to may be already gone. So a way to validate the
pointer is needed - and this pointer comparison approach was chosen -
not by me, I am kindof revising the thing. So my question was to
confirm how reliable is the current verification mechanism. My opinion
is that it is not, since pointer values for different instances (in
time) may conicide.
Well, I'm sure that many people will (rightly so) tell you that if
you free memory, that you should make sure that no pointers to it
will ever be used again.

Short of never free()ing any of your instances (a very bad idea),
or making sure to never reference a free()ed instance (a very good
idea), the only semi-bad solution I see would be to keep track of
all previously-allocated-but-now-freed addresses, and have your
allocate routine check if malloc returned one of them. If so,
keep malloc'ing until a non-previously-used address is returned,
and use that one. (And then free all of the "bad" ones, to keep
from having a memory leak.)

Of course, that "solution" just says "eww, yuck!" to me.

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer .h|
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>
Jul 14 '06 #16
"avasilev" <al********@gma il.comwrote in message
news:11******** **************@ m79g2000cwm.goo glegroups.com.. .
[snip]
No no, Im no examining the moemory that hte pointer points to, I am
simply comparing the values of the pointers themselves, i.e. I am
comparing the addresses, not the contents of the memory that is pointed
to.
If p is an invalid pointer, then even:

p; /* Not much of a statement here. */

invokes undefined behavior.
Jul 14 '06 #17

avasilev wrote:
Dann Corbit wrote:
"avasilev" <al********@gma il.comwrote in message
news:11******** **************@ m79g2000cwm.goo glegroups.com.. .
>
avasilev wrote:
>Hi all,
>>
>my question is:
>>
>if i allocate some memory with malloc() and later free it (using
>free()), is there a possibility that a consequent malloc() will
>allocate memort at the same starting address and will return the same
>pointer as the previous malloc(). I would like to have confirmation on
>whether this is practically a concern when pointers are used to
>uniquely identify data structure instances - like in this example:
>>
>int isInstanceValid (myStrict* inst)
>{
> int i;
> for (i=0; i<instCount; ++i)
> if (instances[i] == inst)
> return 1;
>>
> return 0;
>}
>>
>In this example, if an instance is freed, and a pointer to it becomes
>non-valid, and later a new structure is allocated in the list, the
>function will return that the pointer is valid, although it is actually
>not the instance that was originally referred.
>
Ok I will clarify this a bit, sice some people did not get it properly.
I have a list of instance pointers. Every allocated instance is added
to this list and every freed instance is immediately removed from
there. The problem is that copies of these pointers need to be passed
around, and it may happen that when such a copy has to be used, the
instance it points to may be already gone. So a way to validate the
pointer is needed - and this pointer comparison approach was chosen -
not by me, I am kindof revising the thing. So my question was to
confirm how reliable is the current verification mechanism. My opinion
is that it is not, since pointer values for different instances (in
time) may conicide.
If you know for sure that:
1. The pointers in your list are valid pointers (all the bad ones, having
been removed)
2. The pointers in your list point to the appropriate data type

You still have a problem.

Suppose that pointer 0xdeadbeef is some valid "bucket of chicken" pointer in
your list. You assign that pointer to some struct in memory and say,
"Here's your bucket of chicken."
Later on, the pointer 0xdeadbeef gets freed. Now, we have this pointer,
0xdeadbeef and we want to know if it is valid. If we examine our "bucket of
chicken" pointer and say:
pointer 0 in the list is 0xc0ffc0ff. Is pointer 0xc0ffc0ff equal to pointer
0xdeadbeef?

The simple act of examining the contents of the pointer that is storing
0xdeadbeef invokes undefined behavior. Your computer could dump core, or
Scott Nudds could come flying out of your left nostril. Really, it's
practically in the standard. At least comp.std.c made a similar remark
concerning demons some time ago.

No no, Im no examining the moemory that hte pointer points to, I am
simply comparing the values of the pointers themselves, i.e. I am
comparing the addresses, not the contents of the memory that is pointed
to.

Here is another example:

//this is how we add an instance
struct myStruct* newInst()
{
myStruct* inst = (myStruct*) malloc(sizeof myStruct);

//add the new instance to the linked list of instances
inst->next = instList;
instList = inst;
return inst;
}

//this is how we free an instance and remove it form the list
int delInst(myStruc t* inst)
{
myStruct* cur = instList;
while (cur)
{
if (inst == cur)
{
/ /some code to remove from linked list goes here
free(cur);
return 1;
}
cur = cur->next;
}
return 0;
}

int isInstValid(myS truct* inst)
{
myStruct* cur = instList;
while (cur)
{
if (inst == cur) //here we compare the pointers themselves, not
touching hte memory they point to
return 1;
cur = cur->next;
}

return 0;
}
//and this is how we use this stuff

something = newInst();

....... a lot of code aexecuted here and possibly instance was deleted
from the list and freed

if (isInstValid(so mething))
doSomeStuffWith Instance(someth ing);
else
//probably immediately set something to NULL
The problem is that even if 'if (isInstValid(so mething))' returns
true, the instance that 'something' points to may be not the original
one, but one that was allocated later, after the original one was
freed, both having hte same address by coincidence.

Jul 14 '06 #18
"Kenneth Brody" <ke******@spamc op.netwrote in message
news:44******** *******@spamcop .net...
avasilev wrote:
[...]
>Ok I will clarify this a bit, sice some people did not get it properly.
I have a list of instance pointers. Every allocated instance is added
to this list and every freed instance is immediately removed from
there. The problem is that copies of these pointers need to be passed
around, and it may happen that when such a copy has to be used, the
instance it points to may be already gone. So a way to validate the
pointer is needed - and this pointer comparison approach was chosen -
not by me, I am kindof revising the thing. So my question was to
confirm how reliable is the current verification mechanism. My opinion
is that it is not, since pointer values for different instances (in
time) may conicide.

Well, I'm sure that many people will (rightly so) tell you that if
you free memory, that you should make sure that no pointers to it
will ever be used again.

Short of never free()ing any of your instances (a very bad idea),
or making sure to never reference a free()ed instance (a very good
idea), the only semi-bad solution I see would be to keep track of
all previously-allocated-but-now-freed addresses, and have your
allocate routine check if malloc returned one of them. If so,
keep malloc'ing until a non-previously-used address is returned,
and use that one. (And then free all of the "bad" ones, to keep
from having a memory leak.)

Of course, that "solution" just says "eww, yuck!" to me.
It sounds a little to me like the data structure is upside down, or
disconnected.

Can the list of pointers to objects manage the links to external references?

I would like to know more about the problem. Why do the external objects
have pointers to a list of things that may disappear? What do they do with
the pointers? Why are the external objects not members of the structs in
the pointer list (e.g as a linked list or something).

I think that the tracking homework is strangely designed and I think that
good answers to the questions will depend on why these foreign objects have
addresses of potentially disappearing objects. Do multiple external items
point to the same list object address? What do they use this address for?

How can an external object from the list tell the difference between a
pointer to an object originally allocated to them verses a pointer to a
similar object (allocated with the same address) but allocated for a
different set of external objects?
--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer .h|
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th***** ********@gmail. com>


Jul 14 '06 #19
"avasilev" <al********@gma il.comwrote in message
news:11******** *************@b 28g2000cwb.goog legroups.com...
Here is another example:

//this is how we add an instance
struct myStruct* newInst()
{
myStruct* inst = (myStruct*) malloc(sizeof myStruct);

//add the new instance to the linked list of instances
inst->next = instList;
instList = inst;
return inst;
}

//this is how we free an instance and remove it form the list
int delInst(myStruc t* inst)
{
myStruct* cur = instList;
while (cur)
{
if (inst == cur)
{
/ /some code to remove from linked list goes here
free(cur);
return 1;
}
cur = cur->next;
}
return 0;
}

int isInstValid(myS truct* inst)
{
myStruct* cur = instList;
while (cur)
{
if (inst == cur) //here we compare the pointers themselves, not
This comparison invokes undefined behavior. It may not make your computer
dump core, but it could -- especially if you change compilers or move to
another platform.
touching hte memory they point to
return 1;
cur = cur->next;
}

return 0;
}
//and this is how we use this stuff

something = newInst();

...... a lot of code aexecuted here and possibly instance was deleted
from the list and freed

if (isInstValid(so mething))
doSomeStuffWith Instance(someth ing);
else
//probably immediately set something to NULL
The problem is that even if 'if (isInstValid(so mething))' returns
true, the instance that 'something' points to may be not the original
one, but one that was allocated later, after the original one was
freed, both having hte same address by coincidence.
Yes, this is a real possibility.

What about a doubly linked list? Add a doubly linked list to the main data
structure, and use that list exclusively for creating objects that refer
back to the parent. The child objects can find their parents, and the
parent objects can find their children.
Jul 14 '06 #20

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

Similar topics

33
2735
by: Chris Fogelklou | last post by:
What is wrong with the above? Don't worry, I already know (learned my lesson last week.) It is for the benefit of our resident compiler guru who seems to think you need the cast. I thought it too, up until I started posting here! Thanks, Chris
24
3835
by: David Mathog | last post by:
If this: int i,sum; int *array; for(sum=0, i=0; i<len; i++){ sum += array; } is converted to this (never mind why for the moment):
4
1826
by: Manu | last post by:
Hello, Can we say that the return addresses from the various malloc function calls, in a program, will always be in a predefined order (increasing or decreasing, depeding on how the heap is managed) ? regards Manu
41
3360
by: jacob navia | last post by:
In the C tutorial for lcc-win32, I have a small chapter about a debugging implementation of malloc. Here is the code, and the explanations that go with it. I would appreciate your feedback both about the code and the associated explanations. ---------------------------------------------------------------------
6
3375
by: itsolution | last post by:
Hi folks, Could you shed some light on this issue? my program is running on Freebsd as a daemon. When user sends a request, it forks itself and lets its child process handles the request. And its main role is just to read a big xml file and save each object into its embedded DB(such as gdbm).
0
9855
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
9697
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
10907
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
10586
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10293
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
9426
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...
0
5682
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...
1
4484
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
3
3133
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.