Re: static aray question?
On Wed, 22 Oct 2008 17:23:00 -0700, Robby
<Robby@discussions.microsoft.com> wrote:
Hello,
I am doing some tests in C, in VC++. I am coding stuff but I don't know if
this is acceptable from a proffessional point of view. Please consider the
following snippet:
====================================
#include <stdio.h>
#include <stdlib.h>
typedef struct i{
short v; // I thought we used to be able to use bool type ?????
}w;
typedef struct z{
int x;
w *xxx;
}f;
f *f1(f *h)
{
static w x[] = {1,0,1,1,1,0,0,1,0,0};
h = malloc(sizeof(f));
h->x = 8;
h->xxx = x;
return h;
}
main()
{
int t=0;
f *g;
g does not yet have a value.
g=f1(g);
This invokes undefined behavior by attempting to evaluate g as an
argument of the function call. Since you never use the value of g in
the function, there is no point in passing g as an argument. If you
still believe the function needs an argument, use NULL.
t = g->x;
t = g->xxx[4].v;
free(g);
}
============================================
Questions:
1) Is the contents of the static x[] array is stored in the stack?
No. And why do you care? What part of your program would be
different if the answer were yes?
2) Once the f1() function is executed, the static array x[] will always live
and its contents will always stay in memory until main ends, right?
The static array x is created before any part of your program
executes. It exists from the time main begins execution until your
program terminates. Whether it remains in memory or gets swapped to
disk as part of virtual memory management is something your program
can never determine. Suffice it to say it will be in memory whenever
any part of your program accesses it.
3) My concern is the above programming method involving the array and all,
reccomended? In other words in your opinion is calling data from an array
this way right or wrong.
As always, it depends. Since every time you call f1, you allocate a
new struct and set one of the struct members to point to x, ALL the
structs will point to the same x. If this is acceptable for what your
program needs, then it probably is one possible right way. If not, it
is definitely wrong.
4) I also get the following warning saying that g is uninnitialized. Since g
is only innitialized in f1() function is this an extremely important warning?
First, g is not initialized in f1. It is set by assignment, not
initialization, when f1 returns.
Second, since the warning documents a case of undefined behavior, most
professional programmers would consider it important. Especially in
your case where you have indicated in the past a need to port the code
to another system. There are systems where attempting to evaluate the
address (not the data at the address) of an indeterminate pointer can
crash the system.
--
Remove del for email