Ulrich Eckhardt
8/13/2008 6:32:00 AM
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