473,397 Members | 1,950 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,397 software developers and data experts.

How to catch this?

MN
I wrote a function that do some some computation and returns result as
a char* [5] type. After, I used this function in other program that
executes the same function 10 times, then store each result in each
array's element with type char* big_array[5], so the total length of
big_array must be (5+1)*10, where 1 bit is added to store the '\0'
character .

To show result I used printf (see code 1) and I noticed that if I use
printf in the loop, I see that at each iteration the result changes,
but if I use printf out of loop (see code 2) , I see that only the
last result is shown at each iteration. This mean that at each
iteration the new value given by function erases the old result.
How to avoid this?

My code is like this

/************ code 1 *********************/
char* function (int in1, int in2)
{
static char array [5];

/*do some computation*/

return(array);
}

int main ()
{
int i = 0;
char* big_array [(5+1)*10];
for (i = 0; i<6*9; i=i+6)
{
big_array [i+6] = function( i , 2);

printf("%s\n",big_array [i+6]);
}
return 0;
}

/************** End code 1 *****************/
/************ code 2 *********************/
char* function (int in1, int in2)
{
static char array [5];

/*do some computation*/

return(array);
}

int main ()
{
int i = 0;
int j = 0;
char* big_array [(5+1)*10];
for (i = 0; i<6*9; i=i+6)
{
big_array [i+6] = function( i , 2);
}

for (j=0;j<6*9; j=j+6)
{
printf("%s\n",big_array [j+6]);
}

return 0;
}

/************** End code 2 *****************/
Aug 13 '08 #1
6 1178
On 2008-08-13, MN <ma************@gmail.comwrote:
To show result I used printf (see code 1) and I noticed that if I use
printf in the loop, I see that at each iteration the result changes,
but if I use printf out of loop (see code 2) , I see that only the
last result is shown at each iteration. This mean that at each
iteration the new value given by function erases the old result.
How to avoid this?

My code is like this

/************ code 1 *********************/
char* function (int in1, int in2)
{
static char array [5];

/*do some computation*/

return(array);
}

<snip>
You are returning the address of a static char[5]. Because it is static,
there is only one instance, that is changed every time the function is
called.

So all pointers you assign with the return value of this function will
point to the same place, and therefore doing printf() on them will return
the same value. Does that make sense?

Now, the reason you saw different "correct" results when your printf()
was inside a loop immediately after the call to function() was that
each time your array changed, it was printed before it was changed
again.

HTH.

--
Andrew Poelstra ap*******@wpsoftware.com
To email me, use the above email addresss with .com set to .net
Aug 13 '08 #2
MN wrote:
I wrote a function that do some some computation and returns result as
a char* [5] type. After, I used this function in other program that
executes the same function 10 times, then store each result [...]
[...]
char* function (int in1, int in2)
{
static char array [5];
[..]
return(array);
}
The 'array' inside 'function' is a single object with static duration, i.e.
there will always be only one of it. Calling the function multiple times
will always yield a pointer to the same object, so if you want to store
multiple results, you to make a copy. Otherwise, the next call to the
function will overwrite the former results.

Notes:
- 'return' is not a function, drop those brackets.
- Avoid such uses of function-static objects. They seem convenient, but
they are also dangerous as you see yourself. If you one day make the
program multithreaded, this is far out anyway.
- You could also provide a pointer to where the function should write the
results instead of returning, this is probably the most flexible
alternative.

In general, btw, it is a good idea to document who owns things when passing
them between functions. In this case, it should be documented that the
memory is static, i.e. not owned by the caller. Usually, a called function
only inspects or modifies the data when it receives a pointer or handle. In
other cases, it is the caller's or callee's responsibility to release the
resource. In any case, ownership is something useful to be aware of.

Uli

Aug 13 '08 #3
MN
I understand What you said, but I don't know how to store data before
it gets changed.
Aug 13 '08 #4
MN wrote:
I understand What you said, but I don't know how to store data before
it gets changed.
One way is to copy the array in the caller before calling function()
again.

Aug 13 '08 #5
MN <ma************@gmail.comwrote:
I wrote a function that do some some computation and returns result as
a char* [5] type. After, I used this function in other program that
executes the same function 10 times, then store each result in each
array's element with type char* big_array[5], so the total length of
big_array must be (5+1)*10, where 1 bit is added to store the '\0'
character .
To show result I used printf (see code 1) and I noticed that if I use
printf in the loop, I see that at each iteration the result changes,
but if I use printf out of loop (see code 2) , I see that only the
last result is shown at each iteration. This mean that at each
iteration the new value given by function erases the old result.
How to avoid this?
My code is like this
/************ code 1 *********************/
char* function (int in1, int in2)
{
static char array [5];
/*do some computation*/
return(array);
}
You have already been told about the problems when you return a
pointer to a static array, i.e. that each invokation of the
function returns the same pointer and the elements of the array
get overwritten each time, so you need to make a copy of its
content before you call the function again.
int main ()
{
int i = 0;
char* big_array [(5+1)*10];
for (i = 0; i<6*9; i=i+6)
This looks a bit strange. You ask for an array of 60 pointers to
char but you use only every 6th of them. That together with the
length of the array returned by function() makes it look a bit
as if you actually wanted an array of 60 chars (but you need
only 50 for storing 10 strings returned by function()) and copy
what you get returned by function() into it.

Perhaps what you actually set out to to do is

char big_array[ 10 * 5 ]; /* get a char array with 50 elements */

/* Get 10 strings (of maximum length 5) from function() and
copy them into big_array */

for ( i = 0; i < 10 * 5; i += 5 )
strcpy( &big_array[ i ], function( i, 2 );

for ( i = 0; i < 10 * 5 ; i += 5 )
printf( "%s\n", big_array + i );

return 0;
}

Note that '&big_array[ i ]' and 'big_array + i' are the same, both
being a pointer to the i-th element of 'big_array'.

Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\__________________________ http://toerring.de
Aug 13 '08 #6
MN
Jens Thoms Toerring,
Thanks for your help ! Now my program is working.
Aug 13 '08 #7

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

Similar topics

24
by: Steven T. Hatton | last post by:
If I understand correctly, I have no assurance that I can determine the type of a simple class instance thrown as an exception unless I explicitly catch it by name. (non-derived classes having no...
11
by: kaeli | last post by:
Hey all, I'd like to start using the try/catch construct in some scripts. Older browsers don't support this. What's the best way to test for support for this construct so it doesn't kill...
9
by: Steven Blair | last post by:
Hi, I need to catch exceotions on File.Delete() After checking the help, I have noticed that thgere are serevral Exceptions that can be thrown. My question is, should I catch all thes...
3
by: Steve | last post by:
I have some general catch clauses in my app as follows: try { } catch(Exception ex) { } try
11
by: Pohihihi | last post by:
I was wondering what is the ill effect of using try catch in the code, both nested and simple big one. e.g. try { \\ whole app code goes here } catch (Exception ee) {}
2
by: sbalak | last post by:
I am writing code in C# and I wanted a basic solution: In Try / Catch block, I want to get a general Exception. So, I write code as: try { // do something } catch (SomethingException ex) {
7
by: dick | last post by:
in the "try{throw}catch" structure, how the C++ code return the "type" thrown by a function?
6
by: Jake K | last post by:
I've been reading throught MS article http://support.microsoft.com/kb/306636. I am in the process of learning C# and have a few questions. First, why are the methods (Pause, AddRecord,...)...
13
by: DaTurk | last post by:
What's the CLI equivalent of the empty catch? i.e. try{} catch {}
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...
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...
0
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...
0
agi2029
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,...
0
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...

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.