Results 1 to 3 of 3
Hi ALL,
Recently I faced an interview question from an interviewer:
1. For a class when will be the object is created.
I told that when we use "new" to ...
- 03-02-2010 #1Just Joined!
- Join Date
- May 2009
- Posts
- 21
C++ class object
Hi ALL,
Recently I faced an interview question from an interviewer:
1. For a class when will be the object is created.
I told that when we use "new" to create memory, object will be created.
But again interviewer is asking eventhough u use "new" who will create the object.
Ctype* obj = new CType;
Can you please explain about the object creation.
2. when we are dealing with malloc/free, how free() knows how much memory to be freed. and where is that information is stored. Can you please explain me in detail.
Thanks in Advance,
Madhu
- 03-02-2010 #2Just Joined!
- Join Date
- Aug 2007
- Posts
- 7
I'm not totally sure what question is being asked here either. 'When' is the object created and 'who' creates it are different questions. Did he show you some code when he asked you this question?
It sounds like the answer he was looking for is that the object is created by the constructor function. Objects can be created on the stack, and in this case the new operator will never be called. However if the new operator is called, you are guaranteed that it will invoke the object's constructor.
This is implementation specific, but here's one way free might know how much memory to return.
When you call malloc, you get a pointer to byte X in memory. But when malloc actually allocated that memory, it reserved an extra 4 bytes of space starting at X-4 bytes. In this extra 4 bytes behind the memory it gave to you it stores the size of the chunk of memory it gave you.
When you call free, it simply reads this value back and returns that much memory to the pool.
This is a little bit simplified. There's a bit more book keeping that malloc needs to do to make sure it doesn't allocate the same memory twice, but this is the basic idea.
- 03-02-2010 #3
So I don't fully understand your question 1. What do you mean "who" allocates the memory?
And for question 2, I found this answer by Googling:
C programming : How does free know how much to free? - Stack Overflow
The short answer is that if you ask malloc() to allocate 8 bytes of memory, it will give you a pointer and 8 bytes. Let's suppose it returns to you the address 0x904.
In reality, it has allocated 12 bytes. The 4 bytes from 0x900 - 0x903 are used to store information about the allocation, including how much memory was allocated.DISTRO=Arch
Registered Linux User #388732


Reply With Quote
