Есть задача передовать некоторую структуру в Integer'е.
Сделал так.
type
Container = record
AName: string;
AClass: Integer;
end;
PContainer = ^Container;
function GetContainer(const I: Integer): Container;
begin
Result := PContainer(I)^;
end;
function SetContainer(AContainer: Container): Integer;
var
PC: PContainer;
begin
GetMem(PC, SizeOf(Container));
ZeroMemory(PC, SizeOf(Container));
PC^ := AContainer;
Result := Integer(PC);
end;
procedure FreeContainer(const I: Integer);
begin
FreeMem(PContainer(I));
end;
var
C: Container;
I: Integer;
begin
C.AName := 'name1';
C.AClass := 1;
I := SetContainer(C);
...
C := GetContainer(I);
FreeContainer(I);
...
end.
Мучает вопрос по поводу освобождения памяти. Все ли верно я сделал?
Здравствуйте, Аноним, Вы писали:
У меня в приложении есть подобные вещи , однако для размещения динамических данных я использую стандартную процедуру NEW и для освобождения соответсвенно DISPOSE, что смущает в вашем коде так это то что ваша структура содержит поле типа string , тут интересно какая у вас версия дельфи по моему с 3 или 4 версии в Delphi string это у нас так называемый LongString который является достаточно своеобразным типом . И тут что говорит нам Help Delphi
FreeMem destroys the variable referenced by P and returns its memory to the heap. If P does not point to memory in the heap, a run-time error occurs. If P points to a structure that includes long strings, Variants, dynamic arrays, or interfaces, call Finalize before calling Freemem.
P is a variable of any pointer type previously assigned by the GetMem procedure.
Size specifies the size in bytes of the dynamic variable to dispose of; if specified, it must be exactly the number of bytes previously allocated to that variable by GetMem.
After calling FreeMem, the value of P is undefined. Because subsequent calls to P^ are not caught as errors, it is advisable to call FreeAndNil instead.
Обратим внимание на то что я выделил жирным шрифтом похоже это ваш случай и вам надо еще дополнительно пользовать Finalize , хотя как я понял если использовать new и dispose для работы с динамическими переменными Finalize генерится компилятором автоматически.
" Аноним " <0@users.rsdn.ru> wrote in message
news:2172839@news.rsdn.ru...
> А как быть? Если перед FreeMem() Сделать SetString(PContainer(I)^.AName, nil, 0).
> Или если вместо string использовать PChar и диспойзить ее перед освобождением памяти?
Ответ то читал?
call Finalize before calling FreememPosted via RSDN NNTP Server 2.0