Stack variables vs. Heap variables

Yes, first one creates an array of char pointers in the stack, about 500*4 bytes and second one allocates 500 chars in the heap and points a stack char ptr to them.

Allocating in the stack is easy and fast, but stack is limited, heap is slower but much bigger. Apart from that, stack allocated values are "deleted" once you leave the scope, so it is very good for small local values like primitive variables.

If you allocate too much in the stack you might run out of stack and die, main as all the functions you execute has a stack frame in the stack and all the local variables to the function are stored there, so going too deep into function calling might get you into a stackoverflow as well.

In general is a good rule of thumb to allocate anything that you use often and is bigger than a hundred bytes in the heap, and small variables and pointers in the stack.


Seeing that you wrote

char *buff = (char *)malloc(500);

you probably meant

char buff[500];    instead of 
char* buff[500];

in your first example (so you have a char-array, not an array of pointers to chars)

Yes, "allocation" on the stack is faster because you just increase a pointer stored in the ESP register.

You need heap-variables if you want:

1) more memory than fits in the stack (generally much earlier)

2) pass memory that was allocated by a called function to the calling function.


Your buffs are not equivalent.

The first one (char *buff[500]) is an array of 500 pointers; the 2nd one (char *buff = (char *)malloc(500)) is a pointer.

The pointer (on the stack) points to 500 bytes of memory (if the malloc call succeeded) on the heap.
The array of pointers is on the stack. Its pointers are not initialized.