473,467 Members | 1,680 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

why the value is still available

Hi,
in a function if I have

int * retArray()
{
int a[3] = {102,222,355};

printf("%p ", a);

return a;
}

and then in main()

int *p = retArray();
p++;
printf(" \n%p\n %d", p, *p);

the compiler warning me: ../c_test.c: In function 'retArray':
.../c_test.c:24: warning: function returns address of local variable
and for this why the array variables values are still there ?

I've studied that when the function end the local variables loosing
their values as they
are distroyed and so If I want that they are not destroyed I should use
the static word before them...

Oct 4 '06 #1
12 1373
xdevel wrote:
Hi,
in a function if I have

int * retArray()
{
int a[3] = {102,222,355};

printf("%p ", a);

return a;
}

and then in main()

int *p = retArray();
p++;
printf(" \n%p\n %d", p, *p);

the compiler warning me: ../c_test.c: In function 'retArray':
../c_test.c:24: warning: function returns address of local variable
and for this why the array variables values are still there ?
It is undefined behavior to try to access that pointer, meaning
things could "work",not work, work for a period of time, etc.
I've studied that when the function end the local variables loosing
their values as they
are distroyed and so If I want that they are not destroyed I should use
the static word before them...
You are returning a pointer to a local element of your array.
This array has auto storage, it goes out of scope when the function
ends.
You could have the caller pass in a pointer to storage where your
function can fiddle with.
Oct 4 '06 #2
xdevel wrote:
int * retArray()
{
int a[3] = {102,222,355};

printf("%p ", a);

return a;
}

and then in main()

int *p = retArray();
p++;
printf(" \n%p\n %d", p, *p);
Don't use static.

#include <stdio.h>
#include <stdlib.h>

void doArray(int *a, size_t c)
{
size_t i;

for (i = 0; i < c; i++) printf("%p ", (void *)&a[i]);
printf("\n");

return;
}

int main(void)
{
int a[3] = { 102, 222, 355 };

doArray(a, 3);

return 0;
}}
Oct 4 '06 #3

Christopher Layne ha scritto:
Don't use static.

#include <stdio.h>
#include <stdlib.h>

void doArray(int *a, size_t c)
{
size_t i;

for (i = 0; i < c; i++) printf("%p ", (void *)&a[i]);
printf("\n");

return;
}

int main(void)
{
int a[3] = { 102, 222, 355 };

doArray(a, 3);

return 0;
}
yes but my question was relative to the situation of an array creation
inside a funcion :)

Oct 4 '06 #4
xdevel said:
Hi,
in a function if I have

#include <stdio.h/* don't forget! */

int * retArray()
{
int a[3] = {102,222,355};

printf("%p ", a);
printf("%p ", (void *)a);
>
return a;
Don't do that. The array stops existing when the function returns, so its
address isn't much use to anyone.
}

and then in main()

int *p = retArray();
p++;
printf(" \n%p\n %d", p, *p);
The program's behaviour is undefined, because the value of p is
indeterminate and yet you've tried not only to use it but even to
dereference it.
the compiler warning me: ../c_test.c: In function 'retArray':
../c_test.c:24: warning: function returns address of local variable
and for this why the array variables values are still there ?
One possible outcome of undefined behaviour (although by no means the only
one) is that, on this particular occasion, the program behaves in the way
you observed, and has no unfortunate side-effects such as randomly
corrupting a single bit in your system directory.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Oct 4 '06 #5

Richard Heathfield ha scritto:
One possible outcome of undefined behaviour (although by no means the only
one) is that, on this particular occasion, the program behaves in the way
you observed, and has no unfortunate side-effects such as randomly
corrupting a single bit in your system directory.
thanks you are always clear and precise in your answers.

Oct 4 '06 #6
Ark
Christopher Layne wrote:
<snip>
Don't use static.
<snip>
int main(void)
{
int a[3] = { 102, 222, 355 };

doArray(a, 3);

return 0;
}
There is a school of thought that says automatic (basically, on-stack)
arrays are evil. Reason: as a mere mortal, I'm bound to make an
off-by-one mistake sooner or later, and do something unpredictable, like
corrupt the return address of my caller. That's pretty darn hard to debug.
For the most part, I sorta bought into this (arrays are static or
dynamically allocated, which normally comes at a price of access
efficiency).
Is it overly paranoid? Any comments from safety- or mission- critical or
related fields?
Thank you,
-Ark
Oct 5 '06 #7
Ark wrote:
There is a school of thought that says automatic (basically, on-stack)
arrays are evil. Reason: as a mere mortal, I'm bound to make an
off-by-one mistake sooner or later, and do something unpredictable, like
corrupt the return address of my caller. That's pretty darn hard to debug.
I wouldn't write sub-optimal code because of "could happen"'s. The reason I
said don't use static has to do with re-entrancy. Not that using static
automatically makes a function non-reentrance *in-use* - just that in his
particular example that was what he was shooting for.

Also, off-by-one errors are going to screw you if an array is auto or not.
Oct 5 '06 #8
Ark
Christopher Layne wrote:
Ark wrote:
>There is a school of thought that says automatic (basically, on-stack)
arrays are evil. Reason: as a mere mortal, I'm bound to make an
off-by-one mistake sooner or later, and do something unpredictable, like
corrupt the return address of my caller. That's pretty darn hard to debug.

I wouldn't write sub-optimal code because of "could happen"'s.
That's the notion of "defensive programming". People do it all the time.
The reason I
said don't use static has to do with re-entrancy. Not that using static
automatically makes a function non-reentrance *in-use* - just that in his
particular example that was what he was shooting for.

Also, off-by-one errors are going to screw you if an array is auto or not.
True. But if I corrupt data only, I have a better chance of successful
debugging.

- Ark
Oct 5 '06 #9
Ark wrote:
That's the notion of "defensive programming". People do it all the time.
I tend to categorize defensive programming as being defensive against
internals (input lengths, maybe-cases, etc) and vague assumptions in code
(proper parenthesizing, not making ridiculous use of operator precedence that
not all may remember) rather than defending against myself, the programmer. I
guess what I'm trying to say is that by adopting a sub-optimal idiom because
you're afraid you *might* screw up is pulling a rug over the real issues.
>Also, off-by-one errors are going to screw you if an array is auto or not.
True. But if I corrupt data only, I have a better chance of successful
debugging.

- Ark
If your debugger is decent - it will be apparent regardless.
Oct 5 '06 #10
Ark wrote:
Christopher Layne wrote:
>Ark wrote:
>>There is a school of thought that says automatic (basically, on-stack)
arrays are evil. Reason: as a mere mortal, I'm bound to make an
off-by-one mistake sooner or later, and do something unpredictable, like
corrupt the return address of my caller. That's pretty darn hard to
debug.

I wouldn't write sub-optimal code because of "could happen"'s.
That's the notion of "defensive programming". People do it all the time.
I would not count avoiding automatic arrays as defensive programming. It
does not prevent you from corrupting anything if you go off the end of
the array.
The reason I
>said don't use static has to do with re-entrancy. Not that using static
automatically makes a function non-reentrance *in-use* - just that in his
particular example that was what he was shooting for.

Also, off-by-one errors are going to screw you if an array is auto or
not.
True. But if I corrupt data only, I have a better chance of successful
debugging.
Depends on the quality of your debugging tools and how clearly your code
is written. In any case, you can easily add statements printing out the
value of the index before doing the access if you think there is a problem.
--
Flash Gordon
Oct 5 '06 #11
Ark posted:
There is a school of thought that says automatic (basically, on-stack)
arrays are evil. Reason: as a mere mortal, I'm bound to make an
off-by-one mistake sooner or later, and do something unpredictable, like
corrupt the return address of my caller.

Yes, you probably are -- which is why we check back over our code, paying the
utmost particular attention to these things.

--

Frederick Gotham
Oct 5 '06 #12
Ark wrote:
Christopher Layne wrote:
<snip>
>Don't use static.
<snip>
>int main(void)
{
int a[3] = { 102, 222, 355 };

doArray(a, 3);

return 0;
}

There is a school of thought that says automatic (basically, on-stack)
arrays are evil. Reason: as a mere mortal, I'm bound to make an
off-by-one mistake sooner or later, and do something unpredictable, like
corrupt the return address of my caller. That's pretty darn hard to debug.
For the most part, I sorta bought into this (arrays are static or
dynamically allocated, which normally comes at a price of access
efficiency).
Is it overly paranoid? Any comments from safety- or mission- critical or
related fields?
Wether an array is dynamically allocated, has static or auto storage
duration bears little impact on being able to do an off-by-one error.
Oct 5 '06 #13

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

Similar topics

4
by: Shufen | last post by:
Hi, I'm a newbie that just started to learn python, html and etc. I have some questions to ask and hope that someone can help me on. I'm trying to code a python script (with HTML) to get...
12
by: Sam Collett | last post by:
How do I remove an item with a specified value from an array? i.e. array values 1,2,2,5,7,12,15,21 remove 2 from array would return 1,5,7,12,15,21 (12 and 21 are NOT removed, duplicates are...
27
by: Abdullah Kauchali | last post by:
Hi folks, Can one rely on the order of keys inserted into an associative Javascript array? For example: var o = new Object(); o = "Adam"; o = "Eve";
6
by: Jerry Camel | last post by:
Basic Web Form... A few text boxes and a checkbox - and a card reader... The effect I want to accomplish is this: The basic credit card fields are there and can be filled out. But if the user...
3
by: ANTISPAM_garycnew_ANTISPAM | last post by:
What is the simplest way to retain the last option value selected in an html select object using javascript? I am currently using a server-side cgi language to accomplish this task, but it adds...
11
by: garyusenet | last post by:
I have 'cli via c# on order', and in the mean time am reading 'Pro C# 2005 and the .NET platform' (Andrew Troelson). I'm just reading about the 'five types defined in the CTS'. Specifically Struct....
17
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - How do I get the value of a form control? -----------------------------------------------------------------------...
11
by: Yarco | last post by:
For example: <?php class Test { private $name = 'yarco'; } $p = new ReflectionPropery('Test', 'name'); print $p->getValue();
6
by: Acrobatic | last post by:
Hello, I know this will be an easy fix--but as of now I'm banging my head against the wall. I need a fresh perspective from the group to see what my problem is: This is a simple accounting...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
1
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...
1
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...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
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 ...

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.