link list pointer comparison

T

Tom Timmermann

In the process of building a link list, I noticed that successive
calls to malloc() return a pointer address that keeps getting larger.
Can I always count on this behavior and so do pointer comparisons like
< or > ? Or is it possible for malloc to return a pointer address
smaller than some previous call ?

TomT
 
E

Emmanuel Delahaye

Tom Timmermann wrote on 08/08/04 :
In the process of building a link list, I noticed that successive
calls to malloc() return a pointer address that keeps getting larger.
Can I always count on this behavior

Certainely not. Any value can come.
and so do pointer comparisons like
< or > ? Or is it possible for malloc to return a pointer address
smaller than some previous call ?

Sure it is.
 
J

Jack Klein

In the process of building a link list, I noticed that successive
calls to malloc() return a pointer address that keeps getting larger.
Can I always count on this behavior and so do pointer comparisons like
< or > ? Or is it possible for malloc to return a pointer address
smaller than some previous call ?

TomT

In addition to what Emmanuel said, realize that comparing pointers
from different calls to memory allocations for order is undefined
behavior.

You may only compare pointers for order if they point to members of
the same array, or one past the end of the same array. For this
purpose, a single object acts as an array of one element.

So this is legal:

int x;
int *ip1 = &x;
int *ip2 = ip1 + 1;

if (ip2 > ip1)

But this is undefined behavior:

T *tp1 = malloc(some_value);
T *tp2 = malloc(some_other_value);

if (tp2 > tp1)

The only legal comparison with defined behavior for pointers that do
not meet the rules in the second paragraph above is to compare them
for equality or inequality:

if (tp1 == tp2) /* defined */
if (tp1 != tp2) /* defined */

Any comparison for order between 'unreleated' pointers is undefined.
 
M

Malcolm

Tom Timmermann said:
In the process of building a link list, I noticed that successive
calls to malloc() return a pointer address that keeps getting larger.
Can I always count on this behavior and so do pointer comparisons like
< or > ? Or is it possible for malloc to return a pointer address
smaller than some previous call ?
No, you cannot count on the behaviour, and you may not even compare two
pointers returned from successive calls to malloc(). This is because the
relational operators are valid for pointers within the same object only (to
allow fast comparisons on architectures that don't have flat memory).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,145
Messages
2,570,826
Members
47,372
Latest member
LucretiaFo

Latest Threads

Top