hi all,
I have to compare an address of structure with an absolute address(this
address signifies the start of a memory component).
Now my question is the follwong code leagal:-
#include <stdio.h>
int main()
{
struct t{
int a;
int b;
}temp;
struct t* ptr=&temp;
if(ptr<0x120000 )
printf("What\n" );
else
printf("The hell\n");
return 0;
}
My concern is the comparision in the if statement because a structure
pointer and an unsigned int are being compared. Can there be an
undefined behaviour in any cases ? 20 1732 vb@gmail.com wrote: hi all, I have to compare an address of structure with an absolute address(this address signifies the start of a memory component). Now my question is the follwong code leagal:-
#include <stdio.h>
int main() { struct t{ int a; int b; }temp;
struct t* ptr=&temp;
if(ptr<0x120000 )
<snip>
The above comparison requires integer to pointer conversion, which
is implementation specific. vb@gmail.com wrote: hi all, I have to compare an address of structure with an absolute address(this address signifies the start of a memory component). Now my question is the follwong code leagal:-
#include <stdio.h>
int main() { struct t{ int a; int b; }temp;
struct t* ptr=&temp;
if(ptr<0x120000 ) printf("What\n" ); else printf("The hell\n"); return 0; }
My concern is the comparision in the if statement because a structure pointer and an unsigned int are being compared. Can there be an undefined behaviour in any cases ?
There are (at least) two errors in the comparison, and
one misunderstandin g. The misunderstandin g first: 0x120000
is probably not an unsigned int. "Probably" because is is
up to the compiler to choose an appropriate type for each
literal constant, and different compilers use different bit
counts for the various integer types. The type of 0x120000
will be the first of { int, unsigned int, long, unsigned long,
long long, unsigned long long } that can represent its value,
and on most systems this will turn out to be either int or
long. As far as I can see, 0x120000 could be an unsigned int
only on a machine with 21-bit integers.
Pedantic digressions aside, on to the substantive problems.
First, as you suspect, it is not possible to compare a pointer
to any flavor of integer, except for the special case of an
integer constant zero (which signifies a null pointer). Pointers
are not numbers; numbers are not pointers. You are trying to
compare apples and orangutans.
You could try to rescue the situation by converting the
integer to a pointer by writing (struct t*)0x120000, but this
doesn't really solve anything even though it may cause the
compiler to stop complaining. The first difficulty is that
even though a cast operator can convert an integer to a pointer
(and vice-versa), the result of the conversion is implementation-
defined and need not be meaningful. In particular, it need not
produce a valid, usable result. You can, if you like, declare
that one orangutan converts to twelve and a half apples and then
claim you've compared them, but such capriciousness is not very
useful: neither the apple nor the orangutan pays any attention
to such nonsensical declarations. They were different to begin
with, and different they remain despite silly babbling.
That said, many machines *do* provide useful conversions
between pointers and at least one kind of integer, so even if
the C language doesn't require anything meaningful you may get
some meaning anyhow. But you're still not out of the woods!
The conversion may produce a valid pointer, but it might not
be a valid `struct t*' pointer -- it might, for example, not
satisfy the alignment requirement for a `struct t' object.
Well, there are seventeen low-order zero bits in the integer
you're using, so the likelihood of misalignment is vanishingly
small. Are we safe yet? Well, no. (What did you expect? ;-)
The next problem is that the relational operators <, <=,=, > can only be applied to pointers that designate locations
in (or just after) the same array. That is
char buff1[100], buff2[100];
char *p = buff1, *q = buff1 + 20;
if (p < q) ... /* okay: both point into buff1 */
q = buff2;
if (p < q) ... /* no good: different arrays */
In your code, ptr points to the object temp (which is thought
of as a one-element array in this context), but 0x120000 even
after conversion is by no means guaranteed to point at or just
after temp. It points (if everything above has gone your way)
to some completely unrelated memory location, and the comparison
can produce completely silly results. (This "same array"
restriction applies to the relational operators but not to the
equality operators: you can use == and != on "unrelated" pointers,
you just can't establish which is "greater.") If you think for
a bit about how the subtraction of pointers is defined, all this
may begin to make some kind of sense.
Summary: Your code might work, once the required cast is
inserted. I'd go so far as to say it would probably work on
most machines. But you're relying on a whole slew of things that
are not guaranteed by the C language; in this sense the code is
neither "leagal" nor legal. Such code may be necessary nonetheless;
some tasks like system-specific memory management are beyond the
capabilities of fully portable C.
--
Eric Sosman es*****@acm-dot-org.invalid
Hi Eric,
Thanks for detailed explaination. Could you clarify me one thing?
Afte casting also, on same machine is the result deterministic? Why I'm
asking is, the pointer address will be virtual address and this may not
be same in different runs.
The &temp may not have same vlaue on the stack frame? If more process'
are running then page replacement can happen and the same value may not
be guarenteed.
Regards,
Raju
Eric Sosman wrote: vb@gmail.com wrote: hi all, I have to compare an address of structure with an absolute address(this address signifies the start of a memory component). Now my question is the follwong code leagal:-
#include <stdio.h>
int main() { struct t{ int a; int b; }temp;
struct t* ptr=&temp;
if(ptr<0x120000 ) printf("What\n" ); else printf("The hell\n"); return 0; }
My concern is the comparision in the if statement because a structure pointer and an unsigned int are being compared. Can there be an undefined behaviour in any cases ?
There are (at least) two errors in the comparison, and one misunderstandin g. The misunderstandin g first: 0x120000 is probably not an unsigned int. "Probably" because is is up to the compiler to choose an appropriate type for each literal constant, and different compilers use different bit counts for the various integer types. The type of 0x120000 will be the first of { int, unsigned int, long, unsigned long, long long, unsigned long long } that can represent its value, and on most systems this will turn out to be either int or long. As far as I can see, 0x120000 could be an unsigned int only on a machine with 21-bit integers.
Pedantic digressions aside, on to the substantive problems. First, as you suspect, it is not possible to compare a pointer to any flavor of integer, except for the special case of an integer constant zero (which signifies a null pointer). Pointers are not numbers; numbers are not pointers. You are trying to compare apples and orangutans.
You could try to rescue the situation by converting the integer to a pointer by writing (struct t*)0x120000, but this doesn't really solve anything even though it may cause the compiler to stop complaining. The first difficulty is that even though a cast operator can convert an integer to a pointer (and vice-versa), the result of the conversion is implementation- defined and need not be meaningful. In particular, it need not produce a valid, usable result. You can, if you like, declare that one orangutan converts to twelve and a half apples and then claim you've compared them, but such capriciousness is not very useful: neither the apple nor the orangutan pays any attention to such nonsensical declarations. They were different to begin with, and different they remain despite silly babbling.
That said, many machines *do* provide useful conversions between pointers and at least one kind of integer, so even if the C language doesn't require anything meaningful you may get some meaning anyhow. But you're still not out of the woods! The conversion may produce a valid pointer, but it might not be a valid `struct t*' pointer -- it might, for example, not satisfy the alignment requirement for a `struct t' object.
Well, there are seventeen low-order zero bits in the integer you're using, so the likelihood of misalignment is vanishingly small. Are we safe yet? Well, no. (What did you expect? ;-)
The next problem is that the relational operators <, <=, >=, > can only be applied to pointers that designate locations in (or just after) the same array. That is
char buff1[100], buff2[100]; char *p = buff1, *q = buff1 + 20; if (p < q) ... /* okay: both point into buff1 */ q = buff2; if (p < q) ... /* no good: different arrays */
In your code, ptr points to the object temp (which is thought of as a one-element array in this context), but 0x120000 even after conversion is by no means guaranteed to point at or just after temp. It points (if everything above has gone your way) to some completely unrelated memory location, and the comparison can produce completely silly results. (This "same array" restriction applies to the relational operators but not to the equality operators: you can use == and != on "unrelated" pointers, you just can't establish which is "greater.") If you think for a bit about how the subtraction of pointers is defined, all this may begin to make some kind of sense.
Summary: Your code might work, once the required cast is inserted. I'd go so far as to say it would probably work on most machines. But you're relying on a whole slew of things that are not guaranteed by the C language; in this sense the code is neither "leagal" nor legal. Such code may be necessary nonetheless; some tasks like system-specific memory management are beyond the capabilities of fully portable C.
-- Eric Sosman es*****@acm-dot-org.invalid
Eric Sosman wrote: vb@gmail.com wrote: hi all, I have to compare an address of structure with an absolute address(this address signifies the start of a memory component). Now my question is the follwong code leagal:-
#include <stdio.h>
int main() { struct t{ int a; int b; }temp;
struct t* ptr=&temp;
if(ptr<0x120000 ) printf("What\n" ); else printf("The hell\n"); return 0; }
My concern is the comparision in the if statement because a structure pointer and an unsigned int are being compared. Can there be an undefined behaviour in any cases ?
There are (at least) two errors in the comparison, and one misunderstandin g. The misunderstandin g first: 0x120000 is probably not an unsigned int. "Probably" because is is up to the compiler to choose an appropriate type for each literal constant, and different compilers use different bit counts for the various integer types. The type of 0x120000 will be the first of { int, unsigned int, long, unsigned long, long long, unsigned long long } that can represent its value, and on most systems this will turn out to be either int or long. As far as I can see, 0x120000 could be an unsigned int only on a machine with 21-bit integers.
Pedantic digressions aside, on to the substantive problems. First, as you suspect, it is not possible to compare a pointer to any flavor of integer, except for the special case of an integer constant zero (which signifies a null pointer). Pointers are not numbers; numbers are not pointers. You are trying to compare apples and orangutans.
You could try to rescue the situation by converting the integer to a pointer by writing (struct t*)0x120000, but this doesn't really solve anything even though it may cause the compiler to stop complaining. The first difficulty is that even though a cast operator can convert an integer to a pointer (and vice-versa), the result of the conversion is implementation- defined and need not be meaningful. In particular, it need not produce a valid, usable result. You can, if you like, declare that one orangutan converts to twelve and a half apples and then claim you've compared them, but such capriciousness is not very useful: neither the apple nor the orangutan pays any attention to such nonsensical declarations. They were different to begin with, and different they remain despite silly babbling.
That said, many machines *do* provide useful conversions between pointers and at least one kind of integer, so even if the C language doesn't require anything meaningful you may get some meaning anyhow. But you're still not out of the woods! The conversion may produce a valid pointer, but it might not be a valid `struct t*' pointer -- it might, for example, not satisfy the alignment requirement for a `struct t' object.
Well, there are seventeen low-order zero bits in the integer you're using, so the likelihood of misalignment is vanishingly small. Are we safe yet? Well, no. (What did you expect? ;-)
The next problem is that the relational operators <, <=, >=, > can only be applied to pointers that designate locations in (or just after) the same array. That is
char buff1[100], buff2[100]; char *p = buff1, *q = buff1 + 20; if (p < q) ... /* okay: both point into buff1 */ q = buff2; if (p < q) ... /* no good: different arrays */
In your code, ptr points to the object temp (which is thought of as a one-element array in this context), but 0x120000 even after conversion is by no means guaranteed to point at or just after temp. It points (if everything above has gone your way) to some completely unrelated memory location, and the comparison can produce completely silly results. (This "same array" restriction applies to the relational operators but not to the equality operators: you can use == and != on "unrelated" pointers, you just can't establish which is "greater.") If you think for a bit about how the subtraction of pointers is defined, all this may begin to make some kind of sense.
Summary: Your code might work, once the required cast is inserted. I'd go so far as to say it would probably work on most machines. But you're relying on a whole slew of things that are not guaranteed by the C language; in this sense the code is neither "leagal" nor legal. Such code may be necessary nonetheless; some tasks like system-specific memory management are beyond the capabilities of fully portable C.
-- Eric Sosman es*****@acm-dot-org.invalid
Is it legal to compare two pointers to different objets ?
eg.
char *str1 = "abcd";
char *str2 = "efg";
then is it legal to compare (str1 < str2) ?
Secondly, can we compare two pointers that are pointing to the
two different members of a structure ?
For eg.
struct test {
int i1;
char * ptr;
int i2;
char c1;
char c2;
}
struct test str_test;
char *c1 = &(str_test.c 1);
int *i1 = &(str_test.i 1);
char *c2 = &(str_test.i 1);
Now, can we compare (i1 < c1) ? I have a doubt because types of i1
and c1 are different ?
I think, comparing (c1 < c2) is more appropriate. ju**********@ya hoo.co.in wrote: Eric Sosman wrote: [...] The next problem is that the relational operators <, <=, >=, > can only be applied to pointers that designate locationsin (or just after) the same array. [...]
Is it legal to compare two pointers to different objets ? eg. char *str1 = "abcd"; char *str2 = "efg"; then is it legal to compare (str1 < str2) ?
No. It is legal to test for equality with == or !=, but
non-portable to test for order with <, <=, >=, >.
Secondly, can we compare two pointers that are pointing to the two different members of a structure ?
Yes. I oversimplified when I wrote about pointers into
the same array. What's actually required is that they point
into or just after the same "aggregate object," which could
be an array, a struct, or a union.
For eg. struct test { int i1; char * ptr; int i2; char c1; char c2; }
struct test str_test; char *c1 = &(str_test.c 1); int *i1 = &(str_test.i 1); char *c2 = &(str_test.i 1);
Now, can we compare (i1 < c1) ? I have a doubt because types of i1 and c1 are different ?
The comparison is disallowed because the two pointers do
not have "compatible types." You could rescue it by rewriting
as `(char*)i1 < c1', essentially treating the struct object as
an array of bytes. Pointers to elements of that byte array
are comparable.
I think, comparing (c1 < c2) is more appropriate.
Yes, that's perfectly all right. So is
int *i2 = &str_test.i2 ;
if (i2 < i1) ...
because of the "same aggregate" rule.
-- Er*********@sun .com
Eric Sosman wrote: ju**********@ya hoo.co.in wrote: [...] For eg. struct test { int i1; char * ptr; int i2; char c1; char c2; }
struct test str_test; char *c1 = &(str_test.c 1); int *i1 = &(str_test.i 1); char *c2 = &(str_test.i 1);
Oops: I missed this error on first reading. You're
trying to initialize a char* variable with an expression
whose type is int*, and since the two types are not
compatible a diagnostic is required. You'd need to
write `char *c2 = (char*)&str_tes t.i1', or perhaps what
I mis-read this as: `char *c2 = &str_test.c2 '.
-- Er*********@sun .com ju**********@ya hoo.co.in wrote: Eric Sosman wrote: vb@gmail.com wrote:
[snip]
Is it legal to compare two pointers to different objets ? eg. char *str1 = "abcd"; char *str2 = "efg"; then is it legal to compare (str1 < str2) ?
Not unless both objects are part of an aggregate object.
(str1 == str2) and (str1 != str2) are legal,
(str1 < str2), (str1 > str2), (str1 <= str2), and (str1 >= str2) are
not.
Secondly, can we compare two pointers that are pointing to the two different members of a structure ?
Yes, because they both point inside the same aggregate object (the
structure).
For eg. struct test { int i1; char * ptr; int i2; char c1; char c2; }
struct test str_test; char *c1 = &(str_test.c 1); int *i1 = &(str_test.i 1); char *c2 = &(str_test.i 1);
Now, can we compare (i1 < c1) ? I have a doubt because types of i1 and c1 are different ?
Correct, they are not compatible types so you cannot compare them.
I think, comparing (c1 < c2) is more appropriate.
That's fine.
Robert Gamble ju**********@ya hoo.co.in writes: Eric Sosman wrote:
[...] The next problem is that the relational operators <, <=, >=, > can only be applied to pointers that designate locations in (or just after) the same array. That is
char buff1[100], buff2[100]; char *p = buff1, *q = buff1 + 20; if (p < q) ... /* okay: both point into buff1 */ q = buff2; if (p < q) ... /* no good: different arrays */
[...] Is it legal to compare two pointers to different objets ? eg. char *str1 = "abcd"; char *str2 = "efg"; then is it legal to compare (str1 < str2) ?
It's legal in the sense that it's not a syntax error or a constraint
violation, so the implementation isn't required to complain about it,
but it invokes undefined behavior.
Secondly, can we compare two pointers that are pointing to the two different members of a structure ? For eg. struct test { int i1; char * ptr; int i2; char c1; char c2; }
struct test str_test; char *c1 = &(str_test.c 1); int *i1 = &(str_test.i 1); char *c2 = &(str_test.i 1);
Now, can we compare (i1 < c1) ? I have a doubt because types of i1 and c1 are different ?
I think, comparing (c1 < c2) is more appropriate.
Any object can be viewed as an array of characters. It's illegal (a
constraint violation requiring a compile-time diagnostic) to compare
pointers to incompatible types, so (i1 < c1) is illegal, but
((char*)i1 < c1) is ok and is guaranteed to yield 1.
--
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.
Eric Sosman <er*********@su n.com> writes: ju**********@ya hoo.co.in wrote:
[...] Secondly, can we compare two pointers that are pointing to the two different members of a structure ?
Yes. I oversimplified when I wrote about pointers into the same array. What's actually required is that they point into or just after the same "aggregate object," which could be an array, a struct, or a union.
And for these purposes, a scalar object can be treated as a
single-element array. For example, the following program will always
print "ok"; ptr1 points just past the end of the "array".
#include<stdio. h>
int main()
{
int x;
int *ptr0 = &x;
int *ptr1 = &x + 1;
if (ptr1 > ptr0) {
printf("ok\n");
}
else {
printf("Somethi ng is broken\n");
}
return 0;
}
--
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. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Peter Rohleder |
last post by:
Hi,
I'm using a style-sheet where I make use of the
XPATH-"following-sibling"-expression.
The part which makes problems looks similar to the following code:
---------------------------
<xsl:for-each select="headdata/extension/person">
|
by: Greener |
last post by:
Hi, I need help badly. Can you do client-side programming instead of
server-side to capture the Browser type info? If this is the case,
what's wrong with the following?
<script language="JavaScript">
function doWord(file)
{
if (navigator.userAgent.indexOf("MSIE")!=-1)
|
by: Greener |
last post by:
May I ask you the following? Two questions about the following block
of code:
1) How to open the file in NON-ReadOnly mode? I tried many things, but
none of them was working.
2) Any problems with the lines with document.write (...), as indicated
below?
|
by: timVerizon |
last post by:
Hoping someone can help here..
Our application (C#.Net) was receiving IBM.Data.DB2.DB2Exceptions
ERROR SQL0904N Unsuccessful execution
caused by an unavailable resource. Reason code: '', type of resource:
'', and resource name: ''. SQLSTATE=57011 .
When looking in db2diag.log, we found the following that seemed to
correspond to each exception:
2005-05-03-08.58.57.470000 Instance:DB2 Node:000
|
by: Shawn |
last post by:
JIT Debugging failed with the following error: Access is denied.
JIT Debugging was initiated by the following account 'PLISKEN\ASPNET'
I get this messag in a dialog window when I try to open an asp.net page. If
I press OK then I get a page with this message:
Server Application Unavailable
The web application you are attempting to access on this web server is
currently unavailable. Please hit the "Refresh" button in your web browser...
| |
by: mike_li |
last post by:
On Window 2000 Professional Server
DB2 UDB
Level:
DB2 code release "SQL07029" with level identifie
"030A0105" and informational tokens "DB2 v7.1.0.98", "n040510" and
"WR21337".
In the db2diag.log,
----------------------------------------------------
2005-12-20-10.05.43.278000 Instance:MC Node:000
|
by: Martin Pritchard |
last post by:
Hi,
Sorry for my ignorance, but I'm a bit new to C++.
I've been handed over a C++ app written in VS2002 which I have to convert to
VS2005. Apparently it's been written in a C style, but cannot comment
myself!
Following the conversion I have numerous errors, which following some
digging around turns out to be because _export is obsolete, and
|
by: dba |
last post by:
using the following code with a problem....
echo "<input type='hidden' name='member_id' value=\"{$row}\">{$row}";
echo "<input type='radio' name='member_name'
value=\"{$row}\">{$row}<br />";
The post_data.php program posts the following
member id is: 0009
|
by: vrsathyan |
last post by:
Hi..,
While executing the following code in purifier..,
std::vector<int> vecX;
vecX.clear();
int iCount = 0;
{
int iVal;
|
by: AllusiveKitten |
last post by:
Hi All
Program:
Microsoft Word 2003
Back ground
I am trying to write a macro to insert a landscape page into a portrait document.
Firstly the code must find out if there is a following page after the current cursor point. If there is a following page, the code need to enter extra section breaks to ensure the footers remain correct, other wise the code will just add an extra page making it landscape.
|
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,...
| |
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...
|
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,...
|
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...
|
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...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |