in reply to Re^7: Perl XS binding to a struct with an array of chars* in thread Perl XS binding to a struct with an array of chars*
I decided to make a little test to see what malloc() is doing
I pretty much always use "Newx" or "Newxz" instead of "malloc" because I read somewhere that they are the recommended XS way of allocating memory.
However, I've always found the 2 alternatives to be interchangeable.
Maybe there are some systems and/or perl configurations where they cannot be used interchangeably but, to my knowledge, I've not encountered such a case.
IME, doing Newx(x, 42, datatype) is effectively the same as doing x=malloc(42 * sizeof(datatype)).
The important difference is that the former allocation must be released by "Safefree", whereas the latter must be released by "free".
Therein lies the sum of my knowledge of memory allocation ;-)
Cheers, Rob
Re^9: Perl XS binding to a struct with an array of chars*
by GrandFather (Saint) on Nov 25, 2022 at 04:09 UTC
|
Probably you already know this, but the z variant zeros the allocated memory (Re^3: help with XS (Newx and) so you pay a little time for possibly a little more safety.
Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond
| [reply] |
Re^9: Perl XS binding to a struct with an array of chars*
by Marshall (Canon) on Nov 25, 2022 at 05:37 UTC
|
There is also safemalloc(). This function also has the warning that only Safefree() should be used to free pointers allocated with safemalloc(). I remember reading somewhere that the reason for Safefree(), safemalloc() and the other XS memory functions has something to do with issues involving threads. Evidently malloc() and free() can get you into trouble with threaded code. Whether or not that also means trouble with even just using a multi-threaded version of Perl albeit without user threads, I don't know.
I used malloc in both test programs just to make them as similar as possible. The Perl XS version should use safemalloc() instead. | [reply] |
|
There is also safemalloc()
Yes, I've only recently become aware of its existence, and I haven't used it at all.
I'm guessing it's just Newx() refactored to mimic the way that malloc() is called.
If I ever see anything to suggest that it offers a significant performance improvement over Newx() then I'll probably switch to it.
Cheers, Rob
| [reply] |
|
Well, these are two completely different functions that have completely different purposes and uses.
void Newx (void* ptr, int nitems, type)
void* safemalloc(size_t size)
I show an application for safemalloc() at Allocate a variable length array inside of a struct where Newx() is just not appropriate. Newx() is only appropriate if the sizeof the type is a constant. | [reply] [d/l] |
|
|
|