M.B said:
Keith Thompson wrote: [...]
In this case, there wasn't really any need to guess. The code causing
the problem was:
struct dirent **namelist;
int n;
n = getFileNames(H5DIR, namelist);
It might as well have been:
struct foo **bar;
int n;
n = bleeble(blah, bar);
Regardless of what struct dirent/struct foo is, and regardless of what
getFileNames() or bleeble() does with its arguments, passing an
uninitialized variable to a function is almost certainly an error.
(Come to think of it, drop the "almost".)
Why do we initialize the variable if the variable is it is being
returned by the called function with a valid value
Because evaluating an uninitialized variable, whether by using it as a
function argument or in some other expression, invokes undefined
behavior.
for ex
void f(int *i)
{
*i=1;
return;
}
int main(void)
{
int k; /*why need int k=0... */
f(&k);
...
return(0);
}
That's not the same thing. There's no need to initialize k, because
you're not passing the value of k to f(); you're merely passing its
address. Within f(), the value of *i is uninitialized garbage, but
that's ok because it doesn't attempt to read it. The value of i is a
valid address (specifically the address of main's k), so there's no
problem referring to i.
------------------
related
----------------------
void f(int i) /* I intend to modify i */
{
i=1;
return;
}
int main(void)
{
int k=0; /*why need int k=0... */
f(k);
...
return(0);
}
No effect on variable "k"
what initialization (0) helps in this case
This f() function is very strangely written. The first thing it does
is assign a value to its parameter, losing whatever value was passed
in by the caller. It would make more sense to declare "void f(void)"
and make i a local variable.
For a realistic function f() that uses the value of its parameter, it
wouldn't make sense to call it with an uninitialized value. Even with
f() as written, if you changed "int k=0;" to "int k;", just evaluating
the value of k invokes undefined behavior. In practice, this is
unlikely to cause any visible symptoms; type int typically doesn't
have any trap representations. You are likely, however, to get a
warning from the compiler.
When you post a followup, please delete any quoted text that isn't
relevant. In particular, don't quote a signature unless you're
actually commenting on the signature. (Deletions are typically marked
with "[...]" or "[snip]".)