structure on a heap memory
This question was recently asked to me in an interview fo开发者_JAVA技巧r which i went confused!!
"How do you initialize a structure in the heap memory ?"
could anybody please tell me the correct answer for this?
btw:how exactly are stack and heap memory are different from each other?
And looking about the above question some might also ask me about how do you initialize a structure on a stack memory?
.
may be this is a basic question or might be a wrong question too, but i am just curious to know!
Could anybody please help?
The stack is used for the allocation of local variables, the heap is used when you dynamically allocate memory, like with malloc(). In either case you will need to make sure you have initialize your structure. You can use something like calloc() to allocate your memory from the heap which automatically zeros it (malloc does not). And the variables on the stack are not initialized as well (if memory serves).
The stack lives exactly as long as the function instance defining it -- when that function intance returns, that memory's free for recycling (if it's housing a proper C++ object w/destructor and all, that dtor will be called). The heap lives until explicitly freed.
"How do you initialize a struct" (on either kind of memory!-) is a peculiar question -- obviously via its automatically called ctor in C++ (if any), otheriwse with a memcpy
or the like -- being in stack or heap makes no difference here.
struct MyStruct
{
int foo;
int bar;
};
...
struct MyStruct* baz = malloc(sizeof(MyStruct));
You can now use baz
, but the values of its members foo and bar are undefined.
Here is my answer to the interview question:
How do you initialize a structure in the heap memory?
- The C++ language does not require a heap.
- In well formed code, the structure should initialize itself in the constructor, prefering initialization in the initialization list.
- Initialize each field individually, using a pointer to the structure. The question could be read to assume that the structure has already been allocated.
- In C, one could use
calloc
, although this assigns zeros to each byte, for some objects this may not be correct.
As far as the difference between a heap and a stack, a stack is a first-in, first-out data structure. Objects are pushed onto the stack, then popped off. A heap is a chunk of memory, in which items are allocated, almost randomly.
Search the web for memory allocation, and memory pools. Many implementations will implement the memory area as a stack that grows towards the heap. The more you allocate from the heap, the less space for the stack and vice-versa.
精彩评论