473,466 Members | 1,396 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

stack and heap

Hello,

I'm confused about heap and stack memories management in C language. Most
books explain that local stack variables for each function are automatically
allocated when function starts and deallocated when it exits. In contrast,
malloc() always takes memory in the heap. Now, let's consider the code as
follows:

int get_buffer()
{
unsigned int head; // local variable?
char *buf; // also local?

char = malloc(100); // allocate memory from heap
...
}

Here is confusion: "char *buf" is supposed to be allocated in stack, on the
other hand, malloc() get memory from heap? How to understand this? Is this
true, that whenever we call malloc (inside of function or outside), we get
memory from heap?

Thank you.

--
Best regards, Roman
Jun 26 '07 #1
9 3134
On 26 Jun, 22:02, "Roman Mashak" <m...@tusur.ruwrote:
Hello,

I'm confused about heap and stack memories management in C language.
C language (as specified by the standard) doesn't say anything
about stack or heap and their management. Specific implementations
might worry about such issues if they are relevant to the platform on
which they run.
Most
books explain that local stack variables for each function are automatically
allocated when function starts and deallocated when it exits.
Which books are those ? Do they claim to speak on standard C or
C on specific operating systems ?
In contrast,
malloc() always takes memory in the heap.
When you say always do you mean on every operating system
on every platform which has a C compiler ? I doubt that this
is true.
Now, let's consider the code as
follows:

int get_buffer()
{
unsigned int head; // local variable?
char *buf; // also local?
If by "local" you mean automatic then the answer is yes.
In other words you won't be able to access the values of
the variables head and buf after the function exits.
char = malloc(100); // allocate memory from heap
I will assume that you meant to write buf instead of char.
There are no guarantees that the memory will be allocated
from the heap or even that such a thing exists on your
platform.
...

}

Here is confusion: "char *buf" is supposed to be allocated in stack, on the
other hand, malloc() get memory from heap? How to understand this?
If you happen to be running the above programme on an
operating system where heap and stack are meaningful
terms then it is likely that buf will be allocated on the
stack and buf from the heap. Let's say that a memory segment
of size of at least 100 bytes is allocated starting at the
address A000. Then the value A000 will be stored in the
area of memory allocated for buf. Note that we have 2
different things here : one is the actual memory which
starts at the address A000 and the other is the value
A000 which can be stored somewhere else , perhaps on
the stack if such a thing exists. In any case for the vast
majority of C programmes you need not worry whether
the memory is allocated on the stack or heap or whatever.
If you think you need to worry then you have probably
misunderstood something.
Is this
true, that whenever we call malloc (inside of function or outside), we get
memory from heap?
Unknown. And for most C programmes you needn't worry
about it.

Jun 26 '07 #2
On 26 Jun, 06:40, Spiros Bousbouras <spi...@gmail.comwrote:
On 26 Jun, 22:02, "Roman Mashak" <m...@tusur.ruwrote:
Here is confusion: "char *buf" is supposed to be allocated in stack, on the
other hand, malloc() get memory from heap? How to understand this?

If you happen to be running the above programme on an
operating system where heap and stack are meaningful
terms then it is likely that buf will be allocated on the
stack and buf from the heap.
Arrrggh , I meant to say that buf will be allocated on the stack
and the area returned by malloc on the heap. But my mistake
gives some insight on why one might get confused.

Jun 26 '07 #3
On 26 Jun, 22:02, "Roman Mashak" <m...@tusur.ruwrote:
I'm confused about heap and stack memories management in C language.
the C standard (the official, definitive definition of the C language)
doesn't mention "stack" or "heap". It talks about "automatic"
variables,
and "dynamic" memory. Automatic variables are created on entry to a
block
(a function is a block) and destroyed on exit. Dynamic memory
is allocated when malloc() (et al) is called and freed when free() (et
al)
is called.

*Some* implemntations use stacks and heaps to implement these things.
Most
books explain that local stack variables for each function are automatically
allocated when function starts and deallocated when it exits.
most books? Assuming the terminology has been corrected...
In contrast,
malloc() always takes memory in the heap.
seems pretty clear to me.
Now, let's consider the code as
follows:

int get_buffer()
{
unsigned int head; // local variable?
char *buf; // also local?

yes, both local to the function
>
char = malloc(100); // allocate memory from heap
...

}

Here is confusion: "char *buf" is supposed to be allocated in stack,
yes...
on the
other hand, malloc() get memory from heap?
yes, it does.
How to understand this?
understand what?
Is this
true, that whenever we call malloc (inside of function or outside), we get
memory from heap?
yes
buf points to the malloc()ed memory. In many implementations
the memory on the stack corresponding to buf holds the address
of the heap memory that has benn malloced
--
Nick Keighley
Jun 26 '07 #4
Nick Keighley wrote:
>
On 26 Jun, 22:02, "Roman Mashak" <m...@tusur.ruwrote:
I'm confused about heap and stack memories management in C language.

the C standard (the official, definitive definition of the C language)
doesn't mention "stack" or "heap".
It talks about "automatic" variables, and "dynamic" memory.
The standard might talk about "dynamic" memory,
but the standard calls it "allocated".

--
pete
Jun 26 '07 #5
On Jun 26, 2:02 pm, "Roman Mashak" <m...@tusur.ruwrote:
>
I'm confused about heap and stack memories management in C language.
The C language doesn't have the concepts of 'stack' and 'heap', it
just has memory. Particular implementations of C may use one or other
of these concepts, and most use both.
Most
books explain that local stack variables for each function are automatically
allocated when function starts and deallocated when it exits. In contrast,
malloc() always takes memory in the heap.
That's a fairly common style of implementation, though small automatic
variables (what you call 'local stack variables') may often get
allocated to registers and not use any memory at all.
Now, let's consider the code as follows:
OK, and let's assume a simplistic C implementation which uses stack
and heap as you describe above.
int get_buffer()
{
unsigned int head; // local variable?
char *buf; // also local?

char = malloc(100); // allocate memory from heap
...

}

Here is confusion: "char *buf" is supposed to be allocated in stack, on the
other hand, malloc() get memory from heap? How to understand this?
What's to understand? You need to explain what you are confused about.
'buf' is a pointer which gets placed on the stack (in this particular
implementation). malloc is a function which allocates memory from the
heap (in this particular implementation). 'head' and 'buf' are
accessible for the duration of function get_buffer and can no longer
be accessed once the function returns. The memory allocated by malloc
is accessible until you explicitly free it.
Is this
true, that whenever we call malloc (inside of function or outside), we get
memory from heap?
You get memory from wherever malloc happens to allocate it, and that
memory is accessible until you explicitly free it.

It's not clear what you are confused about; if you need more help,
please post again and try to be more explicit about your confusion.

Jun 26 '07 #6
On Tue, 26 Jun 2007 14:02:47 -0700, in comp.lang.c , "Roman Mashak"
<mr*@tusur.ruwrote:
>Hello,

I'm confused about heap and stack memories management in C language.
Its really simple - the C /language/ doesn't require either to exist.
Specific /implementations/ may well use stacks and heaps (most do) but
you would need to ask the specialists in your particular compiler for
details, over in a different group. And its unlikely you really need
to know anyway.
>int get_buffer()
{
unsigned int head; // local variable?
char *buf; // also local?
yes, but you can't say anything about where it is allocated from.
char = malloc(100); // allocate memory from heap
possibly, but again C doesn't require this.
>Here is confusion: "char *buf" is supposed to be allocated in stack, on the
other hand, malloc() get memory from heap? How to understand this? Is this
true, that whenever we call malloc (inside of function or outside), we get
memory from heap?
You don't need to know. Seriously. You should just use the correct
allocation method for the object you need, and let the compiler and OS
worry about where to get the memory from.
--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Jun 26 '07 #7
>I'm confused about heap and stack memories management in C language. Most
>books explain that local stack variables for each function are automatically
allocated when function starts and deallocated when it exits. In contrast,
malloc() always takes memory in the heap. Now, let's consider the code as
follows:

int get_buffer()
{
unsigned int head; // local variable?
char *buf; // also local?

char = malloc(100); // allocate memory from heap
...
}

Here is confusion: "char *buf" is supposed to be allocated in stack, on the
other hand, malloc() get memory from heap? How to understand this? Is this
C does not define the terms "stack" and "heap". Some people define
"heap" as "that place from which malloc() obtains its memory", and
define "stack" as "that place from which automatic variables are
allocated". There is no guarantee that *BOTH* places aren't "Fred's
Used Computer Salvage Yard". On the other hand, there's no reason
you can't reverse the definitions of the two, although it's a bit
strange.

There's a difference between a pointer and what it points to. For
example, you put a postal address ("pointer to a residence") on an
envelope. But you cannot fit the actual house on the envelope.
And it looks pretty strange erecting an address complete with postal
code on a residential lot.

The variable "buf" is an automatic variable. The pointer assigned
to buf points at memory from malloc(), assuming malloc() succeeded.
>true, that whenever we call malloc (inside of function or outside), we get
memory from heap?
No. If malloc() fails, you don't get any memory from anywhere.

You can't call malloc() outside of a function.

The variable to which you assign the pointer returned by malloc()
is not in memory returned by *that* call to malloc(), although it
might be in memory from a previous call to malloc() (say, you're
doing linked lists). There's a difference between a pointer variable
and what it points to.

Jun 26 '07 #8
On Jun 26, 2:02 pm, "Roman Mashak" <m...@tusur.ruwrote:
Hello,

I'm confused about heap and stack memories management in C language. Most
books explain that local stack variables for each function are automatically
allocated when function starts and deallocated when it exits. In contrast,
malloc() always takes memory in the heap. Now, let's consider the code as
follows:

int get_buffer()
{
unsigned int head; // local variable?
char *buf; // also local?

char = malloc(100); // allocate memory from heap
...

}

Here is confusion: "char *buf" is supposed to be allocated in stack, on the
other hand, malloc() get memory from heap? How to understand this? Is this
true, that whenever we call malloc (inside of function or outside), we get
memory from heap?
Perhaps you are really asking:
There are these two cans on the shelf that both say "Memory!" but one
of them says 'automatic' and the other one says 'allocated'. Now,
both of those cans have mouth-watering pictures of delicious memory
tidbits... ready for consumption. Which one to try? Are they both
the same flavor? Do they have any bad aftertastes? Which one will a
real memory *connoisseur* choose?

Both of them are wonderful, both for simple snacks and for the main
course, but they also have some subtleties that you must be aware of.

For either one, you can empty the can, and when you reach in for more
-- too bad! It's empty!! :-(

Now, what happens when it is empty is not the same. The 'allocated'
can just comes up empty, and leaves it up to you about what to do with
the missing ingredient for your recipe. On the other hand, the
'automatic' can has a mean trick. When you try to pour some out of
the empty 'automatic' can, razor sharp shards of shredded program
spill all over the floor. Well then, we'll just use 'allocated' all
the time. But not so fast... The 'allocated' can has a mean streak
of its own. You only get to borrow the memory, and if you forget to
put it back in the can, it can cause all kinds of headaches. Big
lumps of it start loafing around and annoying the other dishes that
are being prepared. Before you know it, it fills the whole room like
some water from the 'Sourceror's Apprentice' and nothing useful can be
done. Not only that, but if you should forget to check if the can is
empty, the "gag" address given to you will cause a heinous falling of
your whole cake, and you'll probably burn the cookies.

Oh, and when cooking with hot stuff, don't forget the oven mits.

Jun 26 '07 #9
In article <13*************@corp.supernews.com>,
Gordon Burditt <go***********@burditt.orgwrote:
[without attributions - Stop Doing That]
>>Here is confusion: "char *buf" is supposed to be allocated in stack, on the
other hand, malloc() get memory from heap? How to understand this? Is this

C does not define the terms "stack" and "heap". Some people define
"heap" as "that place from which malloc() obtains its memory", and
define "stack" as "that place from which automatic variables are
allocated". There is no guarantee that *BOTH* places aren't "Fred's
Used Computer Salvage Yard". On the other hand, there's no reason
you can't reverse the definitions of the two, although it's a bit
strange.
There is actually a very good reason not to, at least in one direction:
Automatic variables behave in the way you'd expect if they were placed
on a "stack", in the algorithms-and-data-structures sense of the word.
That is, new automatic variables are created for each new scope[1] entered
and destroyed when that scope is exited, and no scope can be exited until
every scope entered after the entry of that one has been exited, so they
have the last-created, first-destroyed nature that would be expected of
something called a "stack". Dynamically allocated memory does not have
this property, and using the term "stack" to describe something without
this property would make gratuitiously make it much harder for anybody
to understand you.

Not coincidentally, the "stack" (in a different sense of the word: a block
of memory indexed by a register designated by the processor's instruction
set or by a common convention that is moved incrementally as data is
added or removed) that many implementations targeting general-purpose
processors use to store automatic variables behaves in this way, with
the additional useful feature of being able to look at anything that's
currently on the stack instead of being restricted to popping the first
element off (which the algorithms-and-data-structures stack doesn't allow,
but which is Rather Useful for automatic storage in a C program).
(The algorithms-and-data-structures "heap" doesn't map as nicely onto
the properties of mallocated memory, though.)
dave

[1] "Scope" is used informally here, meaning approximately "lexical
block in a unique invocation of a function". So a function calling
another function (including recursively calling itself) creates a
new scope, as does entering a block controlled by a loop statement.

--
Dave Vandervies dj******@csclub.uwaterloo.ca
Shouldn't that be "gedankenmord"? Unless you enjoy getting Germans
wound up by perverting their language. I sure do.
--Steve VanDevender in the scary devil monastery
Jun 27 '07 #10

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

Similar topics

5
by: Anders K. Jacobsen [DK] | last post by:
Hey. Is it possible somehow to persist the call stack, heap, program data...everything. Then at a later time load it again and continue work. The idea is actually to send it all over network in...
0
by: john sutor | last post by:
Does anyone know the difference between the Stack and the Heap?
2
by: tonyhall | last post by:
I am trying to find out how items on the stack are stored, is it a FILO or a FIFO? Also what about the heap? I ask as I have found two articles one stating that the stack is stored as FILO and...
11
by: ZorpiedoMan | last post by:
When you create a new object, when is it added to the heap? More specifically: Sub go(ClassRef as myClass) Dim myObj as new myClass = ClassRef End Sub
13
by: orobalage | last post by:
Hi! I was developing some number-crunching algorithms for my university, and I put the processor into a class. While testing, I found a quite *severe performance problem* when the object was...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
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...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
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
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

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.