PDA

View Full Version : Determining objects allocated on a hip in C++



Гамбринус
08-11-2006, 11:09 AM
I just came across little memory handling problem --

Reconciliator rec(&recon_scenario, new TradeRecordParser(new XXXTradeList), new TradeRecordParser(new YYYTradeList));

Assuming all the classes are conforming to the standards, and object instances are well behaved. The above technique will require some mechanism to delete objects allocated on a hip whilst for Reconciliator there is no indication on how they were allocated. To solve the problem I introduced globally (somewhere at the beginning of main) one integer on a stack and one pointer to integer on the hip, so pointers to instances of the hipped objects will have value greater then pointer to global int* that was hipped, and those of stacked ones less then &int of stacked one.

Finally, the question is -- will that be portable across platforms/compilers/whatever? Any comments are welcome.

Thanks.

Sixteen
08-11-2006, 12:11 PM
I just came across little memory handling problem --

Reconciliator rec(&recon_scenario, new TradeRecordParser(new XXXTradeList), new TradeRecordParser(new YYYTradeList));

Assuming all the classes are conforming to the standards, and object instances are well behaved. The above technique will require some mechanism to delete objects allocated on a hip whilst for Reconciliator there is no indication on how they were allocated. To solve the problem I introduced globally (somewhere at the beginning of main) one integer on a stack and one pointer to integer on the hip, so pointers to instances of the hipped objects will have value greater then pointer to global int* that was hipped, and those of stacked ones less then &int of stacked one.

Finally, the question is -- will that be portable across platforms/compilers/whatever? Any comments are welcome.

Thanks.



не будет работать. в какую сторону растет heap, a в какую сторону
растет stack space, и главное, как один расположен относительно
другого? вот о чем следует подумать.

high addresses
stack grows from high to low


heap grows from low to high
low addresses


1. рекон не должен заниматься мемори менеджментом, потому
что мемори менеджементом должен заниматься аллокатор
2. аллокатор должен знать кто и как аллоцирован
3. для упрощения жизни не следует никогда смешивать стек и
динамическую аллокации для гомогенных обьектов.

4. юз зер буст, boost:shared_ptr


пысы
факинг бритиш и их факинг вайлст

Гамбринус
08-11-2006, 12:20 PM
Well, it works:

...
int* hip_ptr = NULL;
int* stack_ptr = NULL;


int main(int, char**) {

int return_code = 0;

stack_ptr = &return_code;
hip_ptr = new int;

...

Elsewhere:

...

extern int* hip_ptr;
extern int* stack_ptr;

TradeRecordParser::~OlTradeRecordParser() {

(((void*)trades_) > ::hip_ptr)?(delete trades_): (NULL);
}

...

The previous post clearly states the direction of stack and hip growths. My concern is possible implications.

Sixteen
08-11-2006, 12:43 PM
Well, it works:

...
int* hip_ptr = NULL;
int* stack_ptr = NULL;


int main(int, char**) {

int return_code = 0;

stack_ptr = &return_code;
hip_ptr = new int;

...

Elsewhere:

...

extern int* hip_ptr;
extern int* stack_ptr;

TradeRecordParser::~OlTradeRecordParser() {

(((void*)trades_) > ::hip_ptr)?(delete trades_): (NULL);
}

...

The previous post clearly states the direction of stack and hip growths. My concern is possible implications.


у меня впечатление что этот код будет применять delete
к stack-allocated обьектам точно так же как и к heap-allocated
обьектам. потому что stack is always higher than heap.

Scott Myers has written a lot about stack vs heap allocation discrimination.
It is very hard to do.

another implication. in c++ main is not really the first thing to execute.
you have a global object list which will allocate before main is called.

Гамбринус
08-11-2006, 01:50 PM
Here is the printout of pointers values:


stack_ptr -- 0x0012ff54
hip_ptr -- 0x00326698

I guess I’ll stick with this for the time being…

Sixteen
08-11-2006, 02:04 PM
Here is the printout of pointers values:


stack_ptr -- 0x0012ff54
hip_ptr -- 0x00326698

I guess I’ll stick with this for the time being…

а что это за система?

Гамбринус
08-11-2006, 02:14 PM
XP на Писюке с мелкомягким компайлером, но желательно чтоб под Solaris с гцц портабл было...

Гамбринус
08-11-2006, 03:01 PM
...another implication. in c++ main is not really the first thing to execute. you have a global object list which will allocate before main is called.

Yep! That’s another thing to check J --

&stack_ptr -- 0x00457f34
&hip_ptr -- 0x00457f30

Sixteen
08-11-2006, 03:25 PM
XP на Писюке с мелкомягким компайлером, но желательно чтоб под Solaris с гцц портабл было...

а вот это уже не гарантируется. надо проверять где у соляриса
находится стек по отношению к куче и в какую сторону он растет.

и еще надо помнить об одной вещи - динамически аллоцируюшиеся стеки для threads, которые вообще аллоцируются где нибудь на хипе.

будет неприятно если стек-переменная из другого threada будет
стерта оператором delete.