Quote:
Are in C language automatic variables on the stack actually stored in that area of memory,or does memory that belongs to stack only contain pointers to adresses(outside of stack area) where these automatic variables actually reside?
|
Automatic variables are really stored on the stack. Once the stack frame is popped, they may be randomly overwritten. Therefore the following is a very bad idea:
Code:
int* foo() {
int i = 5;
return &i; /* don't do this! */
}
foo() returns a pointer to somewhere in the stack. :P
Quote:
What if automatic variable is an array (char x[4]="hiya") ?
Is on stack stored only a pointer,but actual value ("hiya") is stored in some other place outside of stack?
|
In this case "hiya" is stored in what I think is called the data segment (someone correct me here) when your program loads. Then, when it gets to your declaration (which btw should be char foo[5] = "hiya" or char foo[] = "hiya" because of the '\0' at the end), it puts 5 bytes on the stack and copies "hiya" into them. There isn't actually a separate pointer made in this case. This is why you can't reassign foo to point somewhere alse like you could with a char*.
Quote:
Is memory to where pointers point allocated at run-time and resides somewhere on the Heap?
|
When you declare a pointer, no heap memory is allocated. The pointer is uninitialized and may point somewhere random. You need to allocate memory for it yourself, usually with malloc() and friends. Alternatively, you can set it to the address of some variable that you already have, like "int *p; p = &foo;" The pointer itself exists on the stack. It simply holds an address. You can actually print out this address with the %p escape to printf:
Code:
#include <stdio.h>
int main()
{
int *foo;
int bar;
bar = 5;
foo = &bar;
printf("foo contains %p\n", foo);
return 0;
}
The important idea here is that when you declare a pointer, in no way shape or form does that imply there is memory somewhere that holds a thing to which the pointer is supposed to point.