Hi
sourcePchar := '01234wretyr ywrtyery eryιοηιοπηεςγ ςερρτγπιοξσδφγ σδγποξσδγδγη φδσγηποδσφη χψβνπ]ο σδηγόξσδητ wry weytwrwy wreywrt wertwet wettw wertwet wety567890';
The above, is NOT how the piano plays... You have absolutely *no* memory-allocation before you stuff the 'SourcePchar' full of chars....
When you use pchars, YOU have to do it all, mem-allocation, mem-length, mem-realloc & mem-free...!
That's why it blows up with an AV.
Regards Benny
No, this is perfectly fine (as long as the data is only read). The string data is embedded in a read-only section of the binary (
.rodata or
.rdata) and the
PChar variable receives its address.
Even C, notorious for its lack of a real string type, can embed string data this way. The real pitfall lies with attempting to modificy that data:
char *msg = "hells world";
msg[4] = 'o'; // Access violation - attempting to write to read-only memory
With that being said, this is more of an exception to the general rule that working with
PChar requires attentive manual memory management. But that's not the only issue here:
function compress (dest : Pbyte;
var destLen : cardinal;
const source : array of Byte;
sourceLen : cardinal) : integer;
compress(@destPchar,destLen,@sourcePchar,length(sourcePchar));
The first argument is a
PByte, but you're passing a
PPChar (pointer to pointer to char) because you're superfluously taking the pointer's address; leave out the
@ and allocate some memory, e.g. with
destPchar := GetMem(Round(sourceLen * 1.001 + 0.5) + 12).
The third argument is an
open array of Byte (which IMO is superfluous when an explicit length parameter exists and makes everything less intuitive). In this case you
should get away with reinterpret-casting the source data as such an array with
PByteArray(sourcePChar)^ since the underlying function doesn't use
Length(source) (which would contain garbage).