Hello, I was wandering when and how does the compiler do the memory allocation for custom types, so that would be possible to avoid the use of malloc() and free().
Thanks for help.
BrownB
Hello, I was wandering when and how does the compiler do the memory allocation for custom types, so that would be possible to avoid the use of malloc() and free().
Thanks for help.
BrownB
Code:void my_func ( int n ) { char array[n]; // this array[] life time is that function scope and has n members allocated at runtime. ... }
Let's have a struct type:
If I declare a variable of that type in my function as follows, will it be allocated in memory by the compiler?Code:typedef struct{ int a; int b; .... }MyStruct
or the only way is to do a manual allocation:Code:void MyFunc(void){ MyStruct s; s.a=1; s.b=2; .... }
The question is:Code:void MyFunc(void){ MyStruct *s; s=malloc(sizeof(MyStruct)); s->a=1; s->b=2; .... free(s); }
when does a compiler 'know' how to allocate a declared variable and when doesn't it know?
I'm a PalmOS programmer, and for some system structs there is no need to use a pointer and manually allocate the memory, while for my structures I must do manually the work. I'd like to know how does the compiler work.
Thanks.
BrownB
int b; // memory of b exist in current scope
int b[n]; // memory of b is allocated at runtime if n size couldn't be determined at compile time.
Ok, I finally understand!!
So, every structure can be allocated at compile time if it contains members which size can be known at compile time=>if the sizes are computed using constants.
If a size depends from a runtime variable/value, the structure must be allocated at runtime.
Is this right?
Thanks a lot for help!
BrownB
It doesn't. If you statically declare an array or struct larger than the stack permits it, you will get an segmentation fault.Originally Posted by BrownB
As you can see, immediate 1 and 2 are assigned to locations on the stack, right behind our not-existing parameterlist. (Ignore the Unknownfunction, it's just to prevent GCC from wiping a function without in- or output).Code:MyFunc: pushl %ebp movl %esp, %ebp subl $24, %esp movl $1, -8(%ebp) movl $2, -4(%ebp) leal -8(%ebp), %eax movl %eax, (%esp) call Unknownfunction leave ret
Here of course the memory is allocated dynamically, eax contains the address of the malloc'd memory, movl moves the immediates into *eax and *(eax +1) (if eax were an int pointer).Code:MyFunc2: pushl %ebp movl %esp, %ebp subl $8, %esp movl $8, (%esp) call malloc movl $1, (%eax) movl $2, 4(%eax) movl %eax, (%esp) call free movl %ebp, %esp popl %ebp ret
If you need to know more about how the stack itself is "allocated", have a look at intels x86 reference manual.