473,791 Members | 2,995 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

function return pointer of int?

Hi all,

I am writing a function, which return the pointer of the int. But it
seems to be wrong. Any suggestion?

int * get_p_t(int t) {
return &t;
}

int main()
{
printf("v1\n");
int t = 5;
int * p_t[2];

p_t[0] = &t; // right
p_t[1] = get_p_t(t); //wrong

return 0;
}

Best regards,
Davy
Nov 5 '08
34 2041
On Wed, 05 Nov 2008 18:17:51 +0000, Harald van Dijk wrote:
On Wed, 05 Nov 2008 01:26:57 -0800, vippstar wrote:
>Please don't quote signatures. (the text after --) Also, no, he can't.
I think his function is valid, ie this code is valid:

int *foo(int i) { return &i; }

However even evaluating foo(anything) invokes undefined behavior, since
the object pointed to by the pointer is over its lifetime, and the
pointer becomes indeterminate. (either unspecified value or trap
representation )

You are allowed to call foo. You are even allowed to use its return
value in limited ways (such as comparisons). You are not allowed to
store foo's result in an object, or dereference it.

The behaviour dealing with trap representations is only undefined if you
store them in an object ("produced by a side effect that modifies all or
any part of the object by an lvalue expression that does not have
character type"), or read them from an object ("read by an lvalue
expression that does not have character type"). In this code, if you
call foo and discard its result, the return value is never stored in or
read from an object.

Actually, I'm not sure how the return value could be a trap
representation at all, since it's a value, and the concept of trap
representations applies to objects, but 6.3.2.2p5 (conversions of
integers to pointers) is a clear example of when a non-lvalue expression
may explicitly be a trap representation.
I would like to add that when I posted this, I hadn't noticed the cross-
post. What I said applies to C99; C90 is different here. I do not know
whether C++ in its current form follows C90, C99, or has entirely
different rules regarding indeterminate values.
Nov 5 '08 #21
On Nov 5, 7:17Â*pm, Harald van Dijk <true...@gmail. comwrote:
On Wed, 05 Nov 2008 01:26:57 -0800, vippstar wrote:
Please don't quote signatures. (the text after --) Also, no,
he can't. I think his function is valid, ie this code is
valid:
int *foo(int i) { return &i; }
However even evaluating foo(anything) invokes undefined
behavior, since the object pointed to by the pointer is over
its lifetime, and the pointer becomes indeterminate. (either
unspecified value or trap representation)
You are allowed to call foo. You are even allowed to use its
return value in limited ways (such as comparisons).
Are you sure? It's certainly not the case in C++, and I didn't
think it was the case in C; any use of the pointers value
(lvalue to rvalue conversion) is undefined behavior, so
comparisons are out.

If the invalid pointer is an lvalue expression, you can do
anything with it that doesn't require an lvalue to rvalue
conversion. For example, take its address, or in C++, bind it
to a reference. Which means that you can also memcpy and memcmp
it. (In the actual example, of course, the pointer isn't an
lvalue, so this is irrelevant.)
You are not allowed to store foo's result in an object, or
dereference it.
The behaviour dealing with trap representations is only
undefined if you store them in an object ("produced by a side
effect that modifies all or any part of the object by an
lvalue expression that does not have character type"), or read
them from an object ("read by an lvalue expression that does
not have character type"). In this code, if you call foo and
discard its result, the return value is never stored in or
read from an object.
Is this a change in C99? It's not the case in C++, nor was it
the case in C90.
Actually, I'm not sure how the return value could be a trap
representation at all, since it's a value, and the concept of
trap representations applies to objects, but 6.3.2.2p5
(conversions of integers to pointers) is a clear example of
when a non-lvalue expression may explicitly be a trap
representation.
It looks like the attempts to clean up a rather vague concept
accidentally went too far. (In C++, this wouldn't cause a
problem, because you return a temporary object, and of course,
this object can have a trapping representation, in which case,
you trap. Not sure about C in this regard.)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Nov 5 '08 #22
On Wed, 05 Nov 2008 10:55:16 -0800, James Kanze wrote:
On Nov 5, 7:17Â*pm, Harald van Dijk <true...@gmail. comwrote:
>The behaviour dealing with trap representations is only undefined if
you store them in an object ("produced by a side effect that modifies
all or any part of the object by an lvalue expression that does not
have character type"), or read them from an object ("read by an lvalue
expression that does not have character type"). In this code, if you
call foo and discard its result, the return value is never stored in or
read from an object.

Is this a change in C99? It's not the case in C++, nor was it the case
in C90.
Yes, this is what 6.2.6.1p5 says:
"Certain object representations need not represent a value of the object
type. If the stored value of an object has such a representation and is
read by an lvalue expression that does not have character type, the
behavior is undefined. If such a representation is produced by a side
effect that modifies all or any part of the object by an lvalue
expression that does not have character type, the behavior is
undefined.[*] Such a representation is called a trap representation. "

C99 has dropped C90's wording for reading indeterminate values, and
replaced it with this.

Thanks for a bit of info on C++'s approach to this.
Nov 5 '08 #23
Keith Thompson <ks***@mib.orgw rites:
Puppet_Sock <pu*********@ho tmail.comwrites :
>On Nov 5, 4:26*am, vipps...@gmail. com wrote:
[...]
>>int *foo(int i) { return &i; }

However even evaluating foo(anything) invokes undefined behavior,
since the object pointed to by the pointer is over its lifetime, and
the pointer becomes indeterminate. (either unspecified value or trap
representatio n)

It only becomes undefined if you try to deref the
pointer that gets returned, because it's a pointer
to a local variable, which has gone out of scope
by the time foo returns. There is no problem with
taking the address, or passing the address around.
But if you try to manipulate things through that
address, you open the gates of undefined.

(Ok, whose sock-puppet are you?)

You're mistaken. If you have a pointer to an object, and that object
then ceases to exists, then the pointer value becomes indeterminate,
and any attempt to evaluate the pointer invokes undefined behavior.
What about not doing anything with it?

foo(0);

It's not being assigned to anything, compared to anything, computed
with, dereferenced, or basically anything that could be said to be
"evaluating " the pointer?

Phil
--
We must respect the other fellow's religion, but only in the sense and to the
extent that we respect his theory that his wife is beautiful and his children
smart. -- Henry Louis Mencken (1880-1956), American editor and critic
Nov 6 '08 #24
Phil Carmody <th************ *****@yahoo.co. ukwrites:
Keith Thompson <ks***@mib.orgw rites:
>Puppet_Sock <pu*********@ho tmail.comwrites :
>>On Nov 5, 4:26*am, vipps...@gmail. com wrote:
[...]
>>>int *foo(int i) { return &i; }

However even evaluating foo(anything) invokes undefined behavior,
since the object pointed to by the pointer is over its lifetime, and
the pointer becomes indeterminate. (either unspecified value or trap
representati on)

It only becomes undefined if you try to deref the
pointer that gets returned, because it's a pointer
to a local variable, which has gone out of scope
by the time foo returns. There is no problem with
taking the address, or passing the address around.
But if you try to manipulate things through that
address, you open the gates of undefined.

(Ok, whose sock-puppet are you?)

You're mistaken. If you have a pointer to an object, and that object
then ceases to exists, then the pointer value becomes indeterminate,
and any attempt to evaluate the pointer invokes undefined behavior.

What about not doing anything with it?

foo(0);

It's not being assigned to anything, compared to anything, computed
with, dereferenced, or basically anything that could be said to be
"evaluating " the pointer?
When an expression statement is executed, the expression is evaluated
and its result is discarded. An implementation might reasonably store
the result in an address register; the act of storing an invalid
address in an address register might cause a trap.

But Harald made a very interesting point. The pointer value returned
by foo is indeterminate, meaning that it's either an unspecified value
or a trap representation. But a trap representation is not a value.
His argument is that there's no representation (at least as far as the
language semantics are concerned) until and unless the value is stored
in an object.

On the other hand, this means that the standard's definition of an
indeterminate *value* as either an unspecified value or a trap
*representation * doesn't make a whole lot of sense.

I'm not sure how this should be resolved.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Nov 6 '08 #25
On 11ÔÂ5ÈÕ, ÏÂÎç3ʱ06·Ö, Davy <zhushe...@gmai l.com>wrote:
On Nov 5, 2:49 pm, Ian Collins <ian-n...@hotmail.co mwrote:
Davy wrote:
Hi all,
I am writing a function, which return the pointer of the int. But it
seems to be wrong. Any suggestion?
int * get_p_t(int t) {
return &t;
}
t is effectively a local variable in get_p_t. So the address you return
will be invalid after the function returns.

Hi Ian, thank you,

But how can I get the address of t in the main() scope, if I want to
use function?


--
Ian Collins- Òþ²Ø±»ÒýÓÃÎÄ×Ö -

- ÏÔʾÒýÓõÄÎÄ×Ö -


void *fun(int i)
{
void *p = &i;
p += (1<<5) + 4;

return p;
}
Nov 6 '08 #26
On Wed, 5 Nov 2008 22:30:03 -0800 (PST), ba**********@16 3.com wrote:
>On 11??5??, ????3??06??, Davy <zhushe...@gmai l.comwrote:
>On Nov 5, 2:49 pm, Ian Collins <ian-n...@hotmail.co mwrote:
Davy wrote:
Hi all,
I am writing a function, which return the pointer of the int. But it
seems to be wrong. Any suggestion?
int * get_p_t(int t) {
return &t;
}
t is effectively a local variable in get_p_t. So the address you return
will be invalid after the function returns.

Hi Ian, thank you,

But how can I get the address of t in the main() scope, if I want to
use function?


--
Ian Collins- ?????????????? -

- ?????????????? -

void *fun(int i)
{
void *p = &i;
p += (1<<5) + 4;

return p;
}
What do you think this accomplishes?

Your first executable statement contains a constraint violation. If
you ignore that (some compilers do as an extension), it invokes
undefined behavior if sizeof(int) < 36. If you have a system with
really large int, then the value returned still becomes indeterminate
as soon as the function returns.

--
Remove del for email
Nov 6 '08 #27
On Nov 6, 7:39 am, Barry Schwarz <schwa...@dqel. comwrote:
On Wed, 5 Nov 2008 22:30:03 -0800 (PST), baichuan0...@16 3.com wrote:
[...]
void *fun(int i)
{
void *p = &i;
p += (1<<5) + 4;
return p;
}
What do you think this accomplishes?
Your first executable statement contains a constraint violation.
I'm not sure what you mean by the "first executable statement".
The definition of p (with its initialization) definitely
generates executable code, and is executed. And there's no
problem with this statement; it is legal and well defined, and
must work in any implementation.

The second statement, of coruse, is ill formed. Pointer
arithmetic is illegal on pointers to void. This is a
constraint violation, which requires a diagnostic.
If you ignore that (some compilers do as an extension), it
invokes undefined behavior if sizeof(int) < 36.
If you have invoked the compiler in a non-conformant mode, what
it does is defined by the compler. If a compiler accepts the
second statement above, you can no longer argue about the code
with regards to the language. For that matter, technically,
once the compiler has issued the diagnostic, it has fulfilled
its obligation, and the rest is undefined behavior. (QoI
issues, of course, introduce additional constraints, but as far
as the standard is concerned, a compiler that reformats your
hard disk anytime you try to compile an ill-formed program is
compliant. The compiler could even document that it's
diagnostic message was to turn on the light of the hard disk
drive for an indeterminate time---I don't think that the
standard formally requires the diagnostic to be text.)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Nov 6 '08 #28
Keith Thompson wrote:
....
But Harald made a very interesting point. The pointer value returned
by foo is indeterminate, meaning that it's either an unspecified value
or a trap representation. But a trap representation is not a value.
His argument is that there's no representation (at least as far as the
language semantics are concerned) until and unless the value is stored
in an object.
More to the point, the only cases associated with trap representations
where the C standard explicitly says the behavior is undefined are the
creation of a trap representation in an object by any method other than
use of an lvalue of character type, or by attempting to access the value
of an object that already contains a trap representation.
On the other hand, this means that the standard's definition of an
indeterminate *value* as either an unspecified value or a trap
*representation * doesn't make a whole lot of sense.
I think that the fundamental problem was the decision of the C committee
to define an indeterminate "value" as including, as one possibility, a
trap "representation ". It should probably have been called an
"indetermin ate representation" , but that would have required rewriting
every place in the standard that currently uses "indetermin ate value",
and the rewrite would be substantially clumsier than the current wording.

In particular, such a change would make it more complicated to describe
what is going wrong in this particular program: returning a pointer from
a function that becomes invalid precisely because of the fact the
function has returned. Maybe we also need the concept of a "trap value",
distinct from the idea of a "trap representation" ?
Nov 6 '08 #29
James Kanze <ja*********@gm ail.comwrites:
On Nov 6, 7:39 am, Barry Schwarz <schwa...@dqel. comwrote:
>On Wed, 5 Nov 2008 22:30:03 -0800 (PST), baichuan0...@16 3.com wrote:

[...]
>void *fun(int i)
{
void *p = &i;
p += (1<<5) + 4;
return p;
}
>What do you think this accomplishes?
>Your first executable statement contains a constraint violation.

I'm not sure what you mean by the "first executable statement".
The definition of p (with its initialization) definitely
generates executable code, and is executed. And there's no
problem with this statement; it is legal and well defined, and
must work in any implementation.
The cross-post is confusing matters (as always!).

In C there is a clear distinction between declarations and statements,
both in the formal syntax as well as in the less formal text of the
standard, so "the first statement" refers unambiguously to the
increment of p (and the extra "executable " is redundant). In C++, as
you know, there is a "declaratio n statement" so the distinction is
lost. Barry is presumably assuming the code is C.

--
Ben.
Nov 6 '08 #30

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

Similar topics

5
2156
by: amit kumar | last post by:
I am calling a function which returns pointer to a map. The declaration of the map is map<int,vectxyz*>. vectxyz is a vector containing pointer to a class xyz. For map<int,vectxyz*>* p1 In the called function, I am using p1->find(1) which is returning a valid iterator and not going to the end. I am returning p1 from the called function. But in the calling function, find(1) is going to the end, i.e unable to find the key 1, which was...
11
2717
by: JKop | last post by:
Take the following simple function: unsigned long Plus5Percent(unsigned long input) { return ( input + input / 20 ); } Do yous ever consider the possibly more efficent:
7
2352
by: George Marshall | last post by:
Hi all, my question is what should I do with a pointer to be used inside a function ? The following function should take a pointer to a null terminated array of chars, do something with it, and write to the other pointer (*dest). Should I check if the *dest pointer is NULL or not before writing to it ? Should I realloc it before I write to it ? Should I free it if != NULL and
8
29070
by: Tweaxor | last post by:
Hey, I was trying to figure out was it possible in C to pass the values in an array from one function to another function. Is the possible in C? ex. y is the array that holds seven values If possible how could one pass these seven values in the array to a function that would check the values. I tried return y but it didn't work
4
3630
by: anonymous | last post by:
Thanks your reply. The article I read is from www.hakin9.org/en/attachments/stackoverflow_en.pdf. And you're right. I don't know it very clearly. And that's why I want to understand it; for it's useful to help me to solve some basic problem which I may not perceive before. I appreciate your help, sincerely.
23
7818
by: bluejack | last post by:
Ahoy... before I go off scouring particular platforms for specialized answers, I thought I would see if there is a portable C answer to this question: I want a function pointer that, when called, can be a genuine no-op. Consider: typedef int(*polymorphic_func)(int param);
17
3265
by: I.M. !Knuth | last post by:
Hi. I'm more-or-less a C newbie. I thought I had pointers under control until I started goofing around with this: ================================================================================ /* A function that returns a pointer-of-arrays to the calling function. */ #include <stdio.h> int *pfunc(void);
3
3658
by: Beta What | last post by:
Hello, I have a question about casting a function pointer. Say I want to make a generic module (say some ADT implementation) that requires a function pointer from the 'actual/other modules' that takes arguments of type (void *) because the ADT must be able to deal with any type of data. In my actual code, I will code the function to take arguments of their real types, then when I pass this pointer through an interface function, I...
11
1961
by: Antoninus Twink | last post by:
What's the correct syntax to define a function that returns a pointer to a function? Specifically, I'd like a function that takes an int, and returns a pointer to a function that takes an int and returns a string. I tried this: gchar *(*f(gint n))(gint) { /* logic here */ }
20
2247
by: MikeC | last post by:
Folks, I've been playing with C programs for 25 years (not professionally - self-taught), and although I've used function pointers before, I've never got my head around them enough to be able to think my way through what I want to do now. I don't know why - I'm fine with most other aspects of the language, but my brain goes numb when I'm reading about function pointers! I would like to have an array of structures, something like
0
9669
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
9515
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
10427
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...
1
10155
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
9995
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
5431
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
5559
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4110
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
2916
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.