473,900 Members | 4,485 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

printing the address of a function


i am trying to print the address of a function without getting a
compiler warning (i am compiling with gcc with alot of flags).

if i try this:

printf("%p", f);

i get:

warning: format %p expects type 'void *; but argument 2 has type 'void
(*) void)'

if i try this:

printf("%p", (void *)f);

i get:

ISO C forbids conversion of function pointer to object pointer type

if i try this:

printf("%x", ((unsigned int)f));

it compiles cleanly, but this solution bugs me because it assumes that
an unsigned int is the same length as a pointer.

any suggestions as to the "correct" way to print the address of a function?

thanks,
rCs

Sep 25 '06
57 5706

Frederick Gotham wrote:
Robert Seacord posted:
ISO C forbids conversion of function pointer to object pointer type


This is the first I have heard of this restriction. The smallest addressable
unit of memory in C is the byte (sidestepping the technicalities of bitfields
and so forth...). Four separate built-in pointer types are guaranteed to
store accurately the address of a byte:
But, with non-flat memory models (and common desktop computers CPU such
as PowerPC or x86 have a non-flat memory model, though many OS and C
implementations give a flat memory model to user space because they
don't give access to the segment registers).
In particular, it means, that, even on a system where
sizeof(any_obje ct_pointer)==si zeof(void*)==si zeof(any_functi on_pointer),
a function pointer may be an address of a byte or anything in a
different segment (e.g. segment indexed by CS instead of DS) than for
object pointers.

I know very well a few memory models used on x86 CPU (and the computer
on which I'm typing this message is an x86) in real mode:
In this mode, many compilers had six memory models:

"Tiny" memory model: 16 bits object pointers and 16 bits function
pointers.
These pointers being addresses of a byte of memory in the same 64KB
segment.
"Small" memory model: 16 bits object pointers and 16 bits function
pointers.
But, these pointers are addresses in a different segment (CS!=DS) and
thus, even if it is possible to convert a function pointer to an object
pointer, exploring such an object pointer doesn't give you the bytes of
the code of the function, but only meaningless bytes!
"Medium" memory model: 16 bits object pointers and 32 bits (the low
order 16 bits word being the offset and the high order 16 bits word
being the segment). Conversions from function pointers to object
pointers are typically forbidden at compile-time.
"Compact" memory model: 32 bits object pointers and 16 bits function
pointers (that's a bit the opposite of the medium memory model).
"Large" memory model: 32 bits object pointers and 32 bits function
pointers (here, they're quite compatible : casting from function to
pointers to object pointers has a sense).
"Huge" memory model: 32 bits object pointers and 32 bits function
pointers, but, with a special pointer arithmetic, the C implementation
transformed a segmented memory model (where an array can't have a size
greater than 65535 bytes) in a flat memory model with the cost of a
slower pointer arithmetic.

Of course that's only a few examples (four examples) of real world
existing memory models where function pointers can't be cast to object
pointers.
I'm conscient there are many other platforms with many other different
memory models where function pointers can't be cast to object pointers
(e.g. embedded CPU where the code memory is a special ROM which is not
accessible via object pointers and with a different size for function
pointers & object pointers).
Sure, the Standard forbids it... but do the laws of physics not guarantee its
success... ?
Because you probably don't know what are physics in the strange world
of memory models.
I guess that with the fact that a few modern popular desktop OS use an
ILP32 *flat* memory model it's easy to feed illusions about what memory
models can exist.

Sep 26 '06 #31
Francis Glassborow wrote:
In article <ef***********@ pc-news.cogsci.ed. ac.uk>, Richard Tobin
<ri*****@cogsci .ed.ac.ukwrites
>Another possibility is that code addresses have the same values as
data addresses but refer to separate memory,
IIRC that is called a Harvard architecture and was also used by some of
the DOS models where different segments were used for data and program.
Except DOS was not Harvard architecture.

But yes, DOS, or rather 16-bit real- and protected- mode environments
typically provided memory models where the (near) pointer to a function
was completely different from a (near) pointer to a data item. They were
offsets into different segments, and while data and code memory was not
physically distinct and could be aliased, the pointers were not
interchangeable .

That said, I don't recall most of these environments being quite ISO C
compliant with regards to pointer handling.
Michal
Sep 26 '06 #32
Francis Glassborow <fr*****@robint on.demon.co.ukw rites:
In article <11************ *********@b28g2 000cwb.googlegr oups.com>,
Robert Gamble <rg*******@gmai l.comwrites
>>If you examine the code snippet above, you will note that you
are converting a pointer to a function into a pointer to an object.

No, I am converting a "pointer *to a pointer* to a function" to a
"pointer to unsigned char".

You may think you are but that is not the way that pointers to
functions work. Given:

void fn(void);

fn and &fn are synonymous (how could they be anything else unless the
second expression was meaningless and Ritchie decided otherwise)
The code in question:

void print_func_addr (void (*fp)()) {
unsigned char *cp = (unsigned char *)&fp;

applies the unary "&" to an object of a pointer-to-function type, not
to the name of the function itself.

--
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.
Sep 26 '06 #33
Robert Seacord wrote:
printf("%x", ((unsigned int)f));
it compiles cleanly, but this solution bugs me because it assumes that
an unsigned int is the same length as a pointer.
There is no standard way to print the value of a pointer to function.
Instead of using unsigned int and %x, you could use uintmax_t and
PRIxMAX. Although it's not guaranteed to work, it's probably your
best shot.
Sep 26 '06 #34
CBFalconer posted:
Answer withheld pending suitable apologies.

Thanks for your input, CBFalconer. Please note that I have taken note of your
position, and shall require no further reminders.

--

Frederick Gotham
Sep 26 '06 #35
Jack Klein posted:
>Four separate built-in pointer types are guaranteed to store accurately
the address of a byte:

char* char signed* char unsigned* void*

(and all their const/volatile/restrict variants.)

Nowhere in the standard does it say that they can address every byte
that exists in a machine, merely every byte that an executable can
access.

I would have thought that that was a given? Maybe I should just be hyper-
specific and start writing ENG at the beginning of every sentence I write
which is in English? ENG What do you think?

>On these grounds, I don't understand the logic pertaining to why we
can't simply do:

void *p = (void*)SomeFunc ;

You are displaying your ignorance of the depth and breadth of systems
on which C is implemented.

Yes, which is why I appended "... ?" to the statement, demonstrating my
ignorance and curiosity.

No, the standard does not forbid it. And the laws of physics have
nothing at all to do with.

Sometimes the laws of physics override what a standard says or doesn't say.
Example: Let's say we have a standard for a particular programming language
which doesn't explictly say whether an unsigned integer type can trap.
However, in a particular part of the standard, it states that an unsigned
integer type shall contain no padding bits. In yet another part of the
standard, it says that the unsigned integer type shall obey modulo
arithmetic of 2^n, where n is the amount of bits in the type.

If we have several such statements, we can put them all together and
realise that, by the laws of physics, an unsigned integer type can't
possibly trap because each and every one of its bit-patterns represents a
valid value.

Granted though, I realise that the laws of physics don't play a part in the
function pointer discussion.

--

Frederick Gotham
Sep 26 '06 #36
On Tue, 26 Sep 2006 11:08:02 +0100, Francis Glassborow
<fr*****@robint on.demon.co.ukw rote in comp.lang.c:
In article <h4************ *************** *****@4ax.com>, Jack Klein
<ja*******@spam cop.netwrites
It just plain does not define any conversions for pointers to
functions, hence any attempt to do so is undefined.

Not that it helps here but I seem to remember that it does define
conversions between different function pointer types.
Agreed, my sentence could have been more detailed.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Sep 26 '06 #37
Frederick Gotham wrote:
....
Sometimes the laws of physics override what a standard says or doesn't say.
Example: Let's say we have a standard for a particular programming language
which doesn't explictly say whether an unsigned integer type can trap.
However, in a particular part of the standard, it states that an unsigned
integer type shall contain no padding bits. In yet another part of the
standard, it says that the unsigned integer type shall obey modulo
arithmetic of 2^n, where n is the amount of bits in the type.

If we have several such statements, we can put them all together and
realise that, by the laws of physics, an unsigned integer type can't
possibly trap because each and every one of its bit-patterns represents a
valid value.
Firstly, you need one addtional thing justify that conclusion, which is
indeed present: a statement of required range of the unsigned integer
type.

Secondly, what you're describing is mathematics, not physics. The laws
of physics are relevant only by making assumptions about the physical
details about how the platform operates. As a test case, consider an
implementation which operates within a human brain. If your "law of
physics" is just as applicable to such an implementation as it is to a
more conventional one, then it probably isn't really a law of physics.

Also, note that in general, the laws allow arbitrarily bad behavior,
for strictly conforming programs, if the platform is damaged in a
suitable fashion while running the program. That's just one of many
different reasons why it's a bad idea to invoke the laws of physics to
resolve questions about the C standard.

Sep 26 '06 #38
On Tue, 26 Sep 2006 20:50:02 GMT, Frederick Gotham
<fg*******@SPAM .comwrote in comp.std.c:
Jack Klein posted:
Four separate built-in pointer types are guaranteed to store accurately
the address of a byte:

char* char signed* char unsigned* void*

(and all their const/volatile/restrict variants.)
Nowhere in the standard does it say that they can address every byte
that exists in a machine, merely every byte that an executable can
access.


I would have thought that that was a given? Maybe I should just be hyper-
specific and start writing ENG at the beginning of every sentence I write
which is in English? ENG What do you think?
I don't understand your reference to "ENG". I did not assume that
your post was in anything other than English, if that is what you are
referring to.

In fact, that statement of mine is actually not quite accurate, due to
not being complete. Better wording for the final clause would be,
"merely every byte that an executable can access as an object".

In any case, you may have thought that this was a given, but taken
together with the rest of your post, I thought you were building a
chain of reasoning that lead to an incorrect conclusion.
On these grounds, I don't understand the logic pertaining to why we
can't simply do:

void *p = (void*)SomeFunc ;
A momentary digression, I am astonished that you did not define the
pointer as "void const *p", with the cast modified accordingly. Back
to the main topic...

Here is where I think (thought) your chain jumps the track. If you
re-read the quotes from your post to here, it implies (to me) that
your concept is:

Given(1): A function SomeFunc() which my program may call (argument
and return type details irrelevant at the moment) and...

Given(2): A pointer to char can point to the address of a byte.

Then(1): The function SomeFunc() must begin at some byte address...

Then(2): This byte address may be stored in a pointer to char (and/or
pointer to void)...

Then(3): Therefore the expression above (void *p = (void*)SomeFunc ;)
must result in something meaningful in relation to the pointer to
function.

Now you happened to what I call "Given(2)" first, so I started out by
commenting on it.

I inferred you to be taking the statement I name "Then(1)" as the
equivalent of an absolute assumption, a third "Given" as it were. This
is true in many cases on many platforms, in fact probably the
overwhelming majority. So for the moment, let's limit the discussion
to those for which this assumption is true.

Somebody else introduced the term "Harvard architecture" quite
correctly, which I neglected to do. There are processors and DSPs,
some of them used in much higher volume than familiar microprocessors
in servers, workstations, and laptops, that actually work this way.

A valid object, say an int named SomeInt, might happen to reside at
address 0x4000. And it could well be that SomeFunc happens to start
at address 0x4000. But this coincidence is meaningless, because they
are in completely separate memory spaces. If you could assign the
address of SomeFunc to a pointer to unsigned char, and examine the
sequence of bytes via that pointer, you would not be examining the
object code of the function, but instead the object representation of
the int SomeInt.

So the point I was trying to make was that even though a pointer to
char (or void) can address a byte, and even a pointer to function
happens to contain the address of the first opcode of the function, it
may be a byte that the pointer to void cannot point to, because it is
in a completely distinct memory space.
No, the standard does not forbid it. And the laws of physics have
nothing at all to do with.

Sometimes the laws of physics override what a standard says or doesn't say.
Example: Let's say we have a standard for a particular programming language
which doesn't explictly say whether an unsigned integer type can trap.
However, in a particular part of the standard, it states that an unsigned
integer type shall contain no padding bits. In yet another part of the
standard, it says that the unsigned integer type shall obey modulo
arithmetic of 2^n, where n is the amount of bits in the type.

If we have several such statements, we can put them all together and
realise that, by the laws of physics, an unsigned integer type can't
possibly trap because each and every one of its bit-patterns represents a
valid value.
Now here is where we are in complete agreement. There are at least
several cases of behavior that the standard does not implicitly state,
but that can be deduced to be well defined from a combination of other
implicit statements that are made.
Granted though, I realise that the laws of physics don't play a part in the
function pointer discussion.
--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Sep 26 '06 #39
Jack Klein wrote:
Robert Seacord posted:
ISO C forbids conversion of function pointer to object pointer type

Actually, the warning is incorrect. The C standard does not forbid
this. It produces undefined behavior by the lack of a definition.
I think that if ____ causes undefined behaviour according to
the ISO C standard, then it is true to say that ISO C forbids ____ .
That is my understanding of the English word "forbid".
It does not matter whether it is explicitly undefined, or
undefined by omission.

Sep 27 '06 #40

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

Similar topics

3
10443
by: gudia | last post by:
I want to Programatically generate Access reports in the pdf format using some tool and then email them to people in the same code. Right now I am trying to do this with pdf995 using VBA (emailing is a separate issue, which pdf995 does not addresses). I downloaded pdf995. It controls printing via pdf995.ini file. In the VBA code, I have DoCmd.OpenReport "Report2", acViewNormal. I am having the following problems right now. (a) I do...
42
9917
by: Prashanth Badabagni | last post by:
Hi, Can any body tell me how to print "hello,world" with out using semicolon Thanks in advance .. Bye Prashanth Badabagni
4
6496
by: Suzanka | last post by:
Hello, I have an application written in C# on visual studio .NET. It is a web aplication. The application consists of many different forms, that users occassionaly want to print out for filing. When they log to application (through web browser) and choose the print option, on the right margin few cm get cut off (so some fields do not print out). Is there any function that ensure that when user pritns he gets the
4
2823
by: CsharpNewcommer | last post by:
Hi I have designed a form containing data and I want to print that form and the data as it appears in the Windows Form. I am a beginner with C# and I have read several "help"s on PrintPage, PrintDialog, etc. but none seem to address the issue of printing directly from the form. They all talk about printing from a text file. Can someone tell me how to print the form and maybe direct me on which to use PrintPage, PrintDialog....which?
7
6786
by: salmonella | last post by:
Hi, I'm trying to print on screen an address of class member function (the function of certain object of course). My code looks like this: class MyClass { public: void fun(void){}; };
9
3026
by: junky_fellow | last post by:
Hi, To print the pointer using printf(), we convert it to (void *) . printf("%p",(void *)ptr); My question is how printf() determine which type of pointer is passed to it and prints its value accordingly ? I have this doubt as different pointers may have different representation and different size. So, how does printf determine
4
2495
by: DeWittds | last post by:
I have asked before and got little responce, So I try and try again. The code below prints the data in the same place but does not advance the page. I can see the lblnumber change but print in top of the previous one. So my loop is working, I have the hasmorepages= true set right after each cycle till the loop finishes. Hopefully someone can point out my error. Thanks David DeWitt this part calls the printing code
8
5922
by: Neo Geshel | last post by:
Greetings. BACKGROUND: My sites are pure XHTML 1.1 with CSS 2.1 for markup. My pages are delivered as application/xhtml+xml for all non-MS web clients, and as text/xml for all MS web clients (Internet Explorer). My flash content was originally brought in via the “flash satay” method, but I have since used some server-side magic do deliver one <objecttag
0
9997
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, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
9845
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,...
1
10978
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
10497
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...
1
8045
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
5892
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...
0
6084
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4305
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3323
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.