Heap-Dynamic or Stack-Dynamic? - heap-memory

Please explain to me if "x" is a Stack-Dynamic variable or Heap-Dynamic variable in this code?And if it is Heap-Dynamic then why it is not Stack-Dynamic variable?Thank you
function foo(){ MyClass x = new MyClass();}

Stack dynamic variables come into existence when you call a function. They exist on the C++ runtime stack, and are temporary. They are either in the parameter list, or declared inside the function (except for statics, which are not instantiated on the stack). These variables disappear when they go out of scope, and the memory for their contents is reclaimed by the runtime.
Heap dynamic instances exist in another area of memory the runtime sets aside called the "heap." These instances come into being via. the "new" operator, and must be explicitly deallocated by the "delete" operator.
I hope this is helpful

I'm not sure what language this is, I'm going to go out on a limb and say it's merely pseudo code, but the concepts should be the same across most of the common OO languages.
Let's break this down:
function foo() {
MyClass x = null;
x = new MyClass();
}
The first line MyClass x = null will allocate some space on the local stack. It's not a lot of space, just enough to store a reference.
The second line x = new MyClass() will do a few things:
Allocate space on the heap for a new instance of MyClass
Call the correct constructor for MyClass
Change the x reference to point to this new instance.
So the simple answer is: it's both.

This specific one is: Dynamic-Heap (I'm assuming you're programming in JAVA here). As to why it's not on the stack?
This allocates memory
It's not an automatic variable
See this article for general directions:
http://www.maxi-pedia.com/what+is+heap+and+stack

Related

Can I use & operator to get a valid pointer in a function even if the function has returned in golang

some code as below
type TUser struct {
Name string
Addr string
}
var UserMap map[int]*TUser //save TUser pointer to map
func LoadUsers() {
... ...
//assume "row" contains the results of table "users" from db
UserMap[0] = &TUser{Name:row["name"], Addr:row["addr"]}
}
My question is:
After the function "LoadUsers" returns, is the pointer in "UserMap[0]" valid?
or it would become a wild pointer like we do the same thing in C language?
Thanks
Yes, this is perfectly valid
From the FAQ:
How do I know whether a variable is allocated on the heap or the stack?
From a correctness standpoint, you don't need to know. Each variable
in Go exists as long as there are references to it. The storage
location chosen by the implementation is irrelevant to the semantics
of the language.
The storage location does have an effect on writing efficient
programs. When possible, the Go compilers will allocate variables that
are local to a function in that function's stack frame. However, if
the compiler cannot prove that the variable is not referenced after
the function returns, then the compiler must allocate the variable on
the garbage-collected heap to avoid dangling pointer errors. Also, if
a local variable is very large, it might make more sense to store it
on the heap rather than the stack.
In the current compilers, if a variable has its address taken, that
variable is a candidate for allocation on the heap. However, a basic
escape analysis recognizes some cases when such variables will not
live past the return from the function and can reside on the stack.

How does the process of memory allocation of dynamic variables?

When a function is called, a space in memory is reserved for local variables (formal parameters and those declared within the function's scope).
I understand that in ANSI C, because it is required that the variables are declared at the beginning of a block.
However, in the case of the following C code compiled with GCC, will the z variable will have its space allocated at the beginning of the block or only when y is equal to 42?
void foo(int x) {
int y;
scanf("%d%*c", &y);
if (y != 42)
return;
int z;
return;
}
Is the behavior the same for other higher level languages such as Python and Ruby, with similar code?
This is typically implemented by reserving space on the stack for all variables that are declared in the method. It would certainly be possible to do it dynamically, but that would require each "potential" variable to internally be represented as a pointer (since its address cannot be known in advance), and the overhead would almost certainly not be worth it. If you really want "dynamic" variables, you can implement it yourself with pointers and dynamic memory allocation.
Java and C# do the same thing: they reserve space for the total collection of local variables.
I don't really know about Python or Ruby, but in these languages, there is no such thing as a primitive data type: all values are references and stored on the heap. As such, it is entirely possible that the storage space for the value referred to by a variable won't appear until the variable "declaration" is executed (although "declaration" isn't really a thing in dynamic languages; it's more of an assignment to a variable that happens do not exist yet). Note, though, that the variable itself also requires storage space (it's a pointer, after all) - however, the variables of dynamic languages are often implemented as hashmaps, so the variables themselves may also dynamically appear and disappear.

Using static instead of malloc - C-language

In my window app made in c (using gtk) I first had to make a pointer to pointer that I sent to a callbackfunction.
Since i sent the pointer to another function I thought I had to allocate memory on the heap for it that is:
GtkWidget **entry;
entry = malloc(5 * sizeof(GtkWidget));
entry[0] = entry_a;
entry[1] = entry_s;
entry[2] = entry_t;
entry[3] = entry_v;
entry[4] = entry_r;
the GtkWidget variable is a local variable
But someone told my that this is not neccessary since it could be declared as static instead
static GtkWidget *entry[5];
correct - the program works using a static GtkVidget-pointer instead. My question is why and what does this static mean in this context?
All variables with a static storage class will have a program execution lifetime and internal linkage; its scope, however, depends on where it is declared.
To address the question you asked, whether to use a static array or mallocing an array is really something that must determined on a case by case basis. For the most part, however, memory is cheap, so you shouldn't have to worry about performance issues one way or the other, unless your array size becomes excessive (an int array size of 5 is rather insignificant). Protecting the integrity of an array is much more of a concern. That is why, as a rule of thumb, you should make a variable's scope as small as possible.
They do different things.
If you allocate an array (or any object) using malloc, that memory is allocated at run time when malloc is called, and it continue to exist until free it (i.e., pass the pointer value returned by malloc to the free function). (realloc can also deallocate malloced space, but that's not relevant here.)
If you define an array object using the static keyword, then the object exists during the entire run time of your program.
The meaning of the static keyword is different depending on where it appears. On a local declaration (inside a function), it gives the object static storage duration, meaning that it exists for the entire execution of the program rather than being deallocated when the function returns. This means it can retain its previous value across calls to the function. An object defined outside any function already has static storage duration; in that case, the static keyword changes its linkage, so it's not visible from other source files.
Which is better, static allocation or malloc? It's impossible to say without more information.
malloc is more flexible. It will report an allocation failure by returning a null pointer; if you declare a static object that's too big, chances are your program will just crash. For an array of just 5 pointers, though, you probably don't need to worry about that (nevertheless, you should always check the value returned by malloc).
Defining a static object only lets you define a single object for each name. malloc lets you build dynamic structures. It also lets you decide at run time how many elements an array needs.
A third alternative is to define an object locally, inside some function definition, without the static keyword. In that case the object will exist only inside that function (or even inside a block), and will be automatically deallocated when the function returns.
Without knowing what you're going to do with your pointer array, we can't tell you how it should be declared and allocated. If you can declare it as a local variable inside some function, you probably should. If you can't, well, don't.

Can a C variable be deleted or removed at any time during the running of a program?

I am wondering if it is possible to delete, that is remove from use, a C variable, say, for example, once the variable is used once?
I was reflecting some time ago on this subject, and one question arose in my mind.
C has many data types and we can create a variable of data type, say integer by the simple code
int i;
Once we have created a variable in this manner, how do we 'delete' it if we do not require it in future use?
I searched on the net, but did not find any C command that does this. By 'k is deleted', I mean 'k has ceased to exist'. I mean, once we do not need the variable, it is a waste, and should be removed.
C does provide the free() function, but it only works on memory allocated using calloc(), malloc(), or realloc().
So how does one remove, say, an int variable, once it has been used?
You don't. The object's lifetime ends once it goes out of scope (it is known as an automatic object, because it is automatically cleaned up).
e.g.
void foo() {
int j = 3;
while (blah) {
int i = 5;
}
// i no longer exists
}
// j no longer exists
In C, there's the concept of storage duration of an object, which determines its lifetime:
static storage lives for the entire execution of the program
thread storage lives till thread termination
automatic storage lives till the surrounding block is left
allocated storage needs explicit de-allocation via free()
Allocated storage aside, the language runtime will take care of reclaiming memory (eg decreasing the stack pointer to discard call frames, which 'frees' automatic storage).

static objects vs. stack- & heap- based objects

I came across the following definition:
A static object is one that exists from the time it is constructed and created until the end of the program. Stack- and Heap- based objects are thus excluded. Static objects are destroyed when the program exits, i.e. their destructors are called when main finishes executing.
Why are stack- and heap- based objects excluded???
Here is what I know about stacks and heaps: The stack is the part of the system memory where all the variables are stored before run-time. The heap is the part of the system memory where all the variables are stored during run-time, e.g. dynamically allocated memory. This means that if I declare an integer variable i in my code and assign the value of say 123 to it, then that will be stored in my stack, because the compiler knows the value during the compile time (before run-time). But if I define a pointer variable and want to initialize it somewhere else, then that will be stored in my heap, since it is unknown to the compiler at the compile time.
There are several storage durations:
Static → whole program lifetime
Automatic (stack) → until the end of the current function
Dynamic (heap) → until it gets explicitly ended (via delete)
"A static object is one that exists from the time it is constructed and created until the end of the program. Stack- and Heap- based objects are thus excluded."
Why are stack- and heap- based objects excluded???
They are "excluded" because they do not exist from the time it is constructed and created until the end of the program.
None of this contradicts what you wrote / understand in your 2nd paragraph, though there may be nuances depending on the programming language that you are talking about.
What you've found is a poorly worded definition of static. Nothing more, nothing less.
In general, a static object is "created" by the compiler at compile time. Its behavior as to program exit is likely to be different across languages. For example, in C, there is no special handling at all (and AFAIK that's also true for Objective-C). Often these objects "live" in a read-only memory area that the compiler created and "attached" to the program. When the program is loaded into memory this read-only area is mapped into the program's memory which is a very fast operation. For example, all the static strings (as in printf("I'm a static string.");) in C are treated that way.
Then there's the stack, aka call stack, and a stack. A stack in general is just a data structure, aka LIFO (last-in-first-out). The call stack is indeed created by the OS and is normally limited in size. It stores all the information that are necessary for function call. That mean for each function call, its arguments and other info is "pushed" to the stack (put on top of the stack) and a little space for the function variables is reserved. Once the function returns, all this stuff is removed and only the return value is left (though even this is not always true, often the return value is passed in a CPU register).
You can store values to the stack, and languages like C++ even allow you to store objects on the stack. They "automatically" get cleaned once its enclosing function returns.
You can store also store a pointer to such an object living in the stack in another variable as well. But what you probably mean is that normally you create an object in the heap (e.g. via new in Java, C++, C#, etc. or alloc in Objective-C) and you get a pointer to that object in return.
Back to the start: static objects are known to the compiler at compile time, but everything that has to do with heap and stack is by definition only known at run time.

Resources