Heap and stack

Hi,

I have a basic doubt here.

Consider the following code snippet:

main()
{
int *a;
.
.
}

Here the memory for a gets allocated in heap or stack.

Hi,
It'll be on stack i suppose and in general all variables declared inside a function will be on stack as well.
You can print the address of where a resides and print the value of stack pointer (SP) you then should have the same base address ...

unsigned long sp(void) {
   asm("movl %esp, %eax");
}
void main() {
  int *a;

  a=malloc(16*sizeof(int));
  printf ("addr of a is %p, sp is %p and malloc is %p\n",&a,sp(),a);
}

Of course i assume you're on intel-based :D!

In the above case, a will point to the memory in the heap storage. Heap because of the malloc.

On the other hand, in the following case, a will point to a memory location in the stack.

int i = 10;
int *a = &i;
main()
{
int *a;
.
.
}

a, itself, is on the stack. What part of memory a "is aimed at" is indeterminate in your code. It could be anywhere. Show us something like a=&some_int and then we can tell you. As it is there is no way to answer.

Next problem - gets works on string pointers, not int *
So I have no idea where gets would be working.

If you are worried about heap being "slower" than stack, don't. Unless you can definitely show that a gets call is a bottleneck - by using a profiler - it is a waste of programmer time to fuss over stuff like that.

gets works against the actual memory referenced by the pointer, it has nothing to do with where the pointer itself lives.

Andryk - void main () is a BAD idea, especially in a UNIX forum.

Memory for both heap and stack is allocated dynamically. The difference is that while stack memory is allocated automatically by the kernel whenever a function is called...heap memory is allocated only-on-request when the program calls malloc(). But as jim mcnamara has pointed out as a programmer you should not fuss over it.

LOL, okay sorry for that, i was just 'quick-coding' to show the diff between vars allocated on stack and on heap ... :o