Hi!
I can't understand what are stacks and how to use them?
When i allocate memory using malloc()-> are these stacks?
Hi!
I can't understand what are stacks and how to use them?
When i allocate memory using malloc()-> are these stacks?
Hope is the first step on the road to disappointment.
Linked lists?
Can you read? If so read the link quzah has posted.
1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
3. Get rid of conio.h and other antiquated DOS crap headers.
4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.
well i just don't know how to use it practically in code...
In C you don't need to "use it practically" as such. If you malloc memory, the memory will be allocated from the heap. That's 'dynamically allocated'. 'Statically allocated' stuff goes on the stack -- statically allocated meaning that the needed memory can be determined at compile time. If you Google "static dynamic memory allocation c" you'll probably find somewhere that explains it better than me. Static = stack, dynamic = heap.
In practice, automatic variables, function arguments, stuff like this:
Some or all of this might end up on the stack. It depends on the ABI of the platform/architecture you're working on (e.g. here's a page on Stack Allocation in MSVC 2010: http://msdn.microsoft.com/en-us/libr...=vs.100).aspx). Not all local variables go on the stack: if they can all fit in registers for the duration of their use, they probably won't go on the stack. Basically when the compiler runs out of registers it'll start spilling things to the stack. Register allocation and stack usage aren't your concern, at least not in the sense of practical use. It's good to understand these things though, can't back that up with why, but I think it's good to know!Code:/* lots of arguments, potentially too many to pass in registers */ void foo (int a, int b, int c, int d, int e, int f, int g) { struct A a; // Big structure (let's say) created without calling malloc int bigArray[1000]; // big ish array int i; int *p = &i; //address of i taken }
A linked list would almost certainly be dynamically allocated, so on the heap, not the stack.
You can allocate memory on the stack directly using the alloca() function, but I suggest you don't do this unless you have a good reason for doing so.
If you want to manually mess with the stack I think you'll generally be better off in assembly language than in a high level language like C, which by design hides such details from you.
Last edited by smokeyangel; 04-08-2012 at 01:45 PM.
Two or more people are are confusing the stack with a stack. It actually matters here which one you are talking about.
Quzah.
Hope is the first step on the road to disappointment.