Reg:Memory allocation

R

raghu

int x;
static int y;
int *p;
int main(void)
{
int i;
int j=9;
int *ptr;
char *str = "GOOGLE";
static int a;
int k[];
int q[]={1,2,3};
register int reg;
volatile int vol;
.......
.....
....
return 0;
}

According to my knowledge the variables declared in the above program
are stored as follows:
GLOBAL VAR's:
x,y are stored in INITIALISED PART OF DATA SEGMENT.
*p is stored in STACK SEGMENT.

LOCAL VAR's:
all variables are stored in STACK SEGMENT.

Am I correct? Please correct if i'm wrong.

Cheers & Regards,
Raghu.
HAPPY NEW YEAR-2008
 
R

Randy Howard

int x;
static int y;
int *p;
int main(void)
{
int i;
int j=9;
int *ptr;
char *str = "GOOGLE";
static int a;
int k[];
int q[]={1,2,3};
register int reg;
volatile int vol;
......
....
...
return 0;
}

According to my knowledge the variables declared in the above program
are stored as follows:
GLOBAL VAR's:
x,y are stored in INITIALISED PART OF DATA SEGMENT.
*p is stored in STACK SEGMENT.

LOCAL VAR's:
all variables are stored in STACK SEGMENT.

Am I correct? Please correct if i'm wrong.

Cheers & Regards,
Raghu.
HAPPY NEW YEAR-2008

You are making a lot of assumptions about the underlying hardware
architecture and the implementation details of a particular development
system. If you want to ask questions about such specifics, find an
appropriate newsgroup. Standard C makes no guarantees about "stack
segments" or "data segments".
 
C

Chris Torek

int x;
static int y;
int *p;

Note that these are all uninitialized, but have static storage
duration (i.e., exist for the lifetime of the entire program),
so are *effectively* initialized as if with "= { 0 }". The
variables have different linkages: x and p have external linkage,
while y has internal linkage.
int main(void)
{
int i;
int j=9;
int *ptr;

These all have automatic duration. The variable named j is
initialized (to 9) and the other two are not.
char *str = "GOOGLE";

The entity named "str", of type "pointer to char", has automatic
duration. It is initialized, and points to an array created by
the compiler. The array created by the compiler may (or may not)
live in read-only memory, but has type char [7] (not the "obviously
correct" type of const char [7] -- in C++ it has this type, but not
in C). The array has static duration, and is initialized to contain
{'G', 'O', 'O', 'G', 'L', 'E', '\0'} (hence the size of 7).
static int a;

The variable "a" has static duration, and is not initialized here,
so is effectively initialized to zero, as if with "= { 0 }".

The array named "k" is missing a size (and is not initialized), which
is a constraint violation, and a diagnostic is required.
int q[]={1,2,3};

The array named "q" is initialized, so its size is computed from
the initializers. It has automatic duration. This declaration is
valid in C99, which allows initializers for automatic-duration
arrays, but not in C89, which does not. If you have a C89 compiler,
a diagnostic is required (of course a single diagnostic for both
the error for the array k and the error for the array q suffices,
although a good compiler will produce two separate diagnostics).
register int reg;
volatile int vol;

These two have automatic duration (and are uninitialized).
......
....
...
return 0;
}
According to my knowledge the variables declared in the above program
are stored as follows:
GLOBAL VAR's:

You need to define what you mean by "global". Some people use this
to mean "any object with static duration", while others use it to
mean "variables that have external linkage". You appear to be doing
the former (which is in my experience not as common as the latter):
x,y are stored in INITIALISED PART OF DATA SEGMENT.
*p is stored in STACK SEGMENT.

These are possible but unlikely. The C Standard says only that
they have static duration -- i.e., that they exist as long as the
C program runs. One way to do that is to put them all on "the
stack" (whatever that may be!) before making the initial call to
main(). In this case, they would all be "stack" variables.

More commonly, however, all three live in a "data segment", but
all three are in the "uninitialized" part of that data segment,
sometimes referred-to as a "bss segment" instead.

(Referring to p as "*p" is also questionable, or at least, a sign
that you have not thought things through here. In particular, p
has type "pointer to int", and -- thanks to its default initialization
because of its static duration -- initial value NULL. The variable
"p" itself thus has a value, but following the pointer value via
"*p" is not valid[%], because the value stored in p is not pointing
to an actual, existing "int". If you set p to point to some "int",
*p becomes valid for as long as that "int" exists. Use a
static-duration object, and *p will be valid as long as p points
to that object; use an automatic-duration object, and *p will be
valid only as long as (a) p points to it and (b) the object itself
is still "alive". The object "dies" when its enclosing block is
terminated.)

[% Following this invalid NULL pointer generally does one of three
things:

"segmentation fault - core dumped" (on most Unix-like systems
such as Linux, and many other protected systems)

is OK to read, producing some semi-predictable value, such
as the first instruction in the program or a copyright string
or some such, but writing to it produces a runtime trap
(perhaps the same "segmentation fault", or "bus error", or
some other machine-specific diagnostic, such as a Blue Screen
of Death or a reboot)

is OK to read and write, but writes are silently ignored

Standard C does not require any of these behaviors, and depending
on any of them is unwise.]
LOCAL VAR's:
all variables are stored in STACK SEGMENT.

Probably, but again, the C Standard does not say so. On at least
a few implementations, there is no separate "stack segment", as
there is no single system-supplied stack. (Either there are multiple
stacks, as on some systems, or there are no distinguished "stacks"
at all, as on others. In the latter case, the C system usually
uses dynamically-allocated space -- sometimes referred to as "the
heap", or sometimes called "free store"; there are some more
less-common names as well -- to create a linked list that functions
in a stack-like manner.)

There is a secondary problem with thinking this way, and that
has to do with those objects that are actually stored in machine
registers (the one named "reg" is perhaps slightly more likely
to be one of these, although modern compilers tend to put as
many variables into registers as possible anyway). The machine
registers are not part of a typical machine's "stack segment",
although in some cases, space is reserved within various stack
frames to hold register values at various times. In that sense,
they may or may not be in a (or the) "stack segment" at any
given point: a variable that is in a register for 10 lines of
code may get written into the stack after those 10 lines, then
taken back into the register 15 lines of code later. It is
thus "on the stack" only sometimes, not all the time.

In summary: if you do not want to be pinned forever to specific
*implementations* of C, avoid making assumptions about "where the
variables live". If you rely only on those things *guaranteed* in
Standard C, your code will work on every Standard C system ever
made. If you rely on things only guaranteed for the Frobozz system,
you may be stuck with the Frobozz system five years from now. Of
course, this is a tradeoff: there is much that is difficult or even
impossible to do only in Standard C, and easy or at least possible
if you limit yourself to particular systems. Just make sure you
know what you are trading: are the magic beans really worth giving
up the cow?
 
C

CBFalconer

raghu said:
.... snip ...

According to my knowledge the variables declared in the above
program are stored as follows:
GLOBAL VAR's:
x,y are stored in INITIALISED PART OF DATA SEGMENT.
*p is stored in STACK SEGMENT.

LOCAL VAR's:
all variables are stored in STACK SEGMENT.

Am I correct? Please correct if i'm wrong.

Wrong. C has no such things as DATA SEGMENT or STACK SEGMENT. It
does have such things as automatic storage, static storage, dynamic
storage, which in turn have the features ascribed to them in the C
standard.

Some useful references about C:
<http://www.ungerhu.com/jxh/clc.welcome.txt>
<http://www.eskimo.com/~scs/C-faq/top.html> (C-faq)
<http://benpfaff.org/writings/clc/off-topic.html>
<http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf> (C99)
<http://cbfalconer.home.att.net/download/n869_txt.bz2> (C99, txt)
<http://www.dinkumware.com/refxc.html> (C-library}
<http://gcc.gnu.org/onlinedocs/> (GNU docs)
<http://clc-wiki.net/wiki/C_community:comp.lang.c:Introduction>
 
J

James Fang

int x;
static int y;
int *p;
int main(void)
{
int i;
int j=9;
int *ptr;
char *str = "GOOGLE";
static int a;
int k[];
int q[]={1,2,3};
register int reg;
volatile int vol;
......
....
...
return 0;

}

According to my knowledge the variables declared in the above program
are stored as follows:
GLOBAL VAR's:
x,y are stored in INITIALISED PART OF DATA SEGMENT.
*p is stored in STACK SEGMENT.

LOCAL VAR's:
all variables are stored in STACK SEGMENT.

Am I correct? Please correct if i'm wrong.

Cheers & Regards,
Raghu.
HAPPY NEW YEAR-2008

why the pointer p allocated in the stack segment?
as far as I am concerned, it should also be allocated in the Data
Segment.
 
M

Mark McIntyre

On Fri, 28 Dec 2007 22:48:39 -0800, raghu wrote:

Snip list of variable declarations & definitions.
According to my knowledge the variables declared in the above program
are stored as follows:

The C standard doesn't say. Some platforms follow the model you suggest,
others don't. If you actually need to know, then you're outside the realm
of C programming. With regard to local variables, you're wrong with at
least one of of them, probably two.
 
R

Rico Secada

On Fri, 28 Dec 2007 22:48:39 -0800 (PST)

Hi Raghu.
int x;
static int y;
int *p;
int main(void)
{
int i;
int j=9;
int *ptr;
char *str = "GOOGLE";
static int a;
int k[];
int q[]={1,2,3};
register int reg;
volatile int vol;
......
....
...
return 0;
}

According to my knowledge the variables declared in the above program
are stored as follows:
GLOBAL VAR's:
x,y are stored in INITIALISED PART OF DATA SEGMENT.
*p is stored in STACK SEGMENT.

LOCAL VAR's:
all variables are stored in STACK SEGMENT.

Am I correct? Please correct if i'm wrong.

None of this matters for writing portable C programs - all that
matters, from the C point of view, is the lifetime of the object. There
are three possible object lifetimes in C - static storage duration,
which applies to file-scope objects and block-scope objects declared
with the static keyword, automatic storage duration, which applies to
all other objects declared at block scope, and dynamic storage
duration, which applies to objects created with malloc(), calloc() or
realloc().

Static storage duration means the object lives for as long as the
program does. Automatic storage duration means the object is created
when the program begins executing the block it's declared in, and ceases
to exist when the end of the block is reached. Dynamic storage
duration means the object is created at the time of the malloc(), calloc
() or realloc () call, and ceases to exist at the time of the
corresponding free().

Best regards!
 
R

raghu

Hi,
I did not get the answer what I wanted.

Cheers,
Raghu
HNY-2008




On Fri, 28 Dec 2007 22:48:39 -0800 (PST)


Hi Raghu.


int x;
static int y;
int *p;
int main(void)
{
int i;
int j=9;
int *ptr;
char *str = "GOOGLE";
static int a;
int k[];
int q[]={1,2,3};
register int reg;
volatile int vol;
......
....
...
return 0;
}
According to my knowledge the variables declared in the above program
are stored as follows:
GLOBAL VAR's:
x,y are stored in INITIALISED PART OF DATA SEGMENT.
*p is stored in STACK SEGMENT.
LOCAL VAR's:
all variables are stored in STACK SEGMENT.
Am I correct? Please correct if i'm wrong.

None of this matters for writing portable C programs - all that
matters, from the C point of view, is the lifetime of the object. There
are three possible object lifetimes in C - static storage duration,
which applies to file-scope objects and block-scope objects declared
with the static keyword, automatic storage duration, which applies to
all other objects declared at block scope, and dynamic storage
duration, which applies to objects created with malloc(), calloc() or
realloc().

Static storage duration means the object lives for as long as the
program does. Automatic storage duration means the object is created
when the program begins executing the block it's declared in, and ceases
to exist when the end of the block is reached. Dynamic storage
duration means the object is created at the time of the malloc(), calloc
() or realloc () call, and ceases to exist at the time of the
corresponding free().

Best regards!
Cheers & Regards,
Raghu.
HAPPY NEW YEAR-2008
 
W

Walter Roberson

raghu said:
Hi,
I did not get the answer what I wanted.

Well to be explicit then, the answer is "NO", C variables are NOT
stored in the locations you believe them to be stored in. One of the
other posters provided a long reply describing where C variables
-are- stored.

Parts of what you described might be true on a particular version
of a particular compiler when used on a particular version of
a specific operating system, but there are real C implementations
around in which -none- of what you described is true -- including
their not having a stack in a form you would recognize.
 
M

Mark McIntyre

Hi,
I did not get the answer what I wanted.

If you knew what answer you wanted, why did you ask?

Anyway lots of people answered your question correctly. You should read
those answers and make sure you understand them.
 
W

William Pursell

The entity named "str", of type "pointer to char", has automatic
duration. It is initialized, and points to an array created by
the compiler.

A few days ago, I stated that a char * is a pointer to
an array, and was (I believe correctly) corrected
by Richard Heathfield that there is a distinction.
This topic seems to come up a lot, and I've finally
realized that the phrase above is correct, but
not in a strictly technical sense. IOW, str
is not a pointer to an array, but it does point
to an array. But the reader should recognize
that stating that str "points to an array" means
that it points to a char which is the first element
of an array.
 
K

Keith Thompson

William Pursell said:
A few days ago, I stated that a char * is a pointer to
an array, and was (I believe correctly) corrected
by Richard Heathfield that there is a distinction.
This topic seems to come up a lot, and I've finally
realized that the phrase above is correct, but
not in a strictly technical sense.

In other words, it's incorrect.
IOW, str
is not a pointer to an array, but it does point
to an array.

It points to the first element of an array.
But the reader should recognize
that stating that str "points to an array" means
that it points to a char which is the first element
of an array.

The reader should recognize that stating that str "points to an array"
means that str is, for example, of type ``char (*)[7]''. In this case
(see above) it isn't, so the statement is incorrect.

Since C actually does have pointers to arrays, using the phrase
"pointer to an array" to mean something else is misleading. If you
have something that's actually of type ``char (*)[7]'', what are you
going to call it if you've already used "pointer to an array" to mean
something else?

(On the other hand, you can correctly say that str "points to a
string", since the standard specifically defines that phrase and
there's no ambiguity. This is because an array is a data type, but a
string is not.)
 
R

Richard Heathfield

CBFalconer said:
You top-posted.

Yet again, you're trying to enforce netiquette without observing it
yourself.
This makes it impossible to get civilized answers.

Rubbish. Top-posting certainly makes an article harder to read, but it
doesn't make it *impossible* to get civilised answers. That's simply
false.
 
C

Chris Torek

[regarding]
A few days ago, I stated that a char * is a pointer to
an array, and was (I believe correctly) corrected
by Richard Heathfield that there is a distinction.

Indeed, I should have said that str points to the first element
of that array. (I was concentrating more on the array itself, the
compiler-created entity that holds the 7 "char"s, when I wrote that.)
 
W

William Pursell

William Pursell said:
A few days ago, I stated that a char * is a pointer to
an array, and was (I believe correctly) corrected
by Richard Heathfield that there is a distinction.
This topic seems to come up a lot, and I've finally
realized that the phrase above is correct, but
not in a strictly technical sense.

In other words, it's incorrect.
IOW, str
is not a pointer to an array, but it does point
to an array.

It points to the first element of an array.
But the reader should recognize
that stating that str "points to an array" means
that it points to a char which is the first element
of an array.

The reader should recognize that stating that str "points to an array"
means that str is, for example, of type ``char (*)[7]''. In this case
(see above) it isn't, so the statement is incorrect.

I disagree. "points to an array" is a colloquialism that
has been in use for a long time that doesn't have the
strict technical meaning that this would ascribe to it.
Since C actually does have pointers to arrays, using the phrase
"pointer to an array" to mean something else is misleading. If you
have something that's actually of type ``char (*)[7]'', what are you
going to call it if you've already used "pointer to an array" to mean
something else?

I agree that "pointer to an array" should be interpreted
to mean "of type char (*)[n]". I think that "points
to an array" does not have the same meaning. Examining
the usage of the phrase shows that to be the case.
Personally, I will try to avoid using the phrase
in the future, but I think it is important to recognize
that it is often used in the non-pedantically-correct
fashion. Consider:

int
main( void )
{
char *a;
char (*b)[8];
void *x;

a = x = xmalloc( 16 );
b = x;

sprintf( a, "fooxbarxbazxqux" );
a[ 3 ] = a[ 7 ] = a[ 11 ] = 0;

return 0;
}

In this case, b is a pointer to an array, and
a is a pointer to a char. They both "point
to an array". b clearly points to an 8 long
array containing the strings "foo" and
"bar", and b + 1 points to an 8 long array
containing the strings "baz" and "qux".
The array that a points to is
ambiguous--it points to the 16 long array
which contains four strings, and it points
to a 2-character array containing 'f' and 'o'.
It points to 17 different arrays, of lengths
0 through 16, respectively. (I'm not sure
that it should be thought of as pointing
to a zero length array.) The semantics of
the phrase are unclear at best, but that
is the common usage.

I don't like this usage, but that is clearly
how C programmers interpret the phrase "points
to an array".

(On the other hand, you can correctly say that str "points to a
string", since the standard specifically defines that phrase and
there's no ambiguity. This is because an array is a data type, but a
string is not.)

So the standard clarifies the meaning of the phrase
"points to a string", but leaves the phrase "points
to an array" ambiguous. When someone like Chris
Torek uses the phrase "points to an array" to describe
an object of type 'char *', I take that to be a
fairly reasonable indicator that competent programmers
use the phrase in that way. (Please note that
I am not simply being argumentative here. I consider
Keith, Chris, and Richard to be extremely valuable
sources of information, and I greatly respect your
input to this group. I'm simply trying to decide
whether or not the phrase "points to an array"
should ever be used in polite company.)
 
K

Keith Thompson

William Pursell said:
The reader should recognize that stating that str "points to an array"
means that str is, for example, of type ``char (*)[7]''. In this case
(see above) it isn't, so the statement is incorrect.

I disagree. "points to an array" is a colloquialism that
has been in use for a long time that doesn't have the
strict technical meaning that this would ascribe to it.

I agree that it's common usage.
Since C actually does have pointers to arrays, using the phrase
"pointer to an array" to mean something else is misleading. If you
have something that's actually of type ``char (*)[7]'', what are you
going to call it if you've already used "pointer to an array" to mean
something else?

I agree that "pointer to an array" should be interpreted
to mean "of type char (*)[n]". I think that "points
to an array" does not have the same meaning.

Hmm. I have trouble with the idea that "pointer to an array" and
"points to an array" have inconsistent meanings.
Examining
the usage of the phrase shows that to be the case.
Personally, I will try to avoid using the phrase
in the future, but I think it is important to recognize
that it is often used in the non-pedantically-correct
fashion.

I agree that's important to recognize the usage, but I'd replace
"non-pedantically-correct" with "incorrect". (Yeah, I'm a pedant;
I don't think that's a bad thing.)

[...]
I don't like this usage, but that is clearly
how C programmers interpret the phrase "points
to an array".

Yes, and I'm trying to correct the error. (Actually, I seem to be
trying to pound it into the ground.)
So the standard clarifies the meaning of the phrase
"points to a string",

Yes. Actually, the standard introduces and defines the phrase.
but leaves the phrase "points
to an array" ambiguous.

No, as far as the standard is concerned there's no ambiguity at all.
When someone like Chris
Torek uses the phrase "points to an array" to describe
an object of type 'char *', I take that to be a
fairly reasonable indicator that competent programmers
use the phrase in that way. (Please note that
I am not simply being argumentative here. I consider
Keith, Chris, and Richard to be extremely valuable
sources of information, and I greatly respect your
input to this group. I'm simply trying to decide
whether or not the phrase "points to an array"
should ever be used in polite company.)

Note that Chris corrected himself elsethread.

Saying that a pointer to the first element of an array "points to the
array" isn't a cardinal sin, and the meaning is *usually* clear enough
from context. And actual pointers to arrays are relatively rare. But
it really is incorrect.
 
D

dj3vande

int q[]={1,2,3};

The array named "q" is initialized, so its size is computed from
the initializers. It has automatic duration. This declaration is
valid in C99, which allows initializers for automatic-duration
arrays, but not in C89, which does not. If you have a C89 compiler,
a diagnostic is required (of course a single diagnostic for both
the error for the array k and the error for the array q suffices,
although a good compiler will produce two separate diagnostics).

Are you sure? I thought aggregate types with constant initializers
were allowed even with automatic duration, and gcc -ansi -pedantic
doesn't complain about it:
--------
dj3vande@buttons:~/clc (0) $ cat array-init.c
int main(void)
{
int q[]={1,2,3};

/*returns 0 (success) if things act as I expect, and 1
(system-specified interpretation, will show up when my
shell prompt displays the exit status) otherwise
*/
return !(sizeof q == 3*sizeof(int));
}
dj3vande@buttons:~/clc (0) $ gcc -W -Wall -ansi -pedantic -O array-init.c
dj3vande@buttons:~/clc (0) $ ./a.out
dj3vande@buttons:~/clc (0) $
--------

(If I'm remembering correctly, I asked about the corresponding change
for struct initialization a few weeks ago, and the response was that
non-constant initialization for objects with aggregate types and
non-static storage duration was the new feature in C99.)


dave
 
C

Chris Torek


Are you sure?

No. My C89 standard is in a box somewhere, and now I think my claim
above was incorrect. In particular:
(If I'm remembering correctly, I asked about the corresponding change
for struct initialization a few weeks ago, and the response was that
non-constant initialization for objects with aggregate types and
non-static storage duration was the new feature in C99.)

I now think this is correct -- the C89 limitation is that all the
initializers for any automatic aggregate must be constants.

(I think PCC, one of the pre-C89 "K&R" compilers, did not accept
any kind of automatic aggregate initializers, even if all the
elements were constant.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,754
Messages
2,569,526
Members
44,997
Latest member
mileyka

Latest Threads

Top