Chapter 8
Dereferencing
Once you know what kind of object an RV points to, you can safely cast the return
value to the correct type:
AV *av;
if (SvTYPE(SvRV(sv_rv)) == SVt_PVAV) {
av = (AV *) SvRV(sv_rv); // safely cast dereferenced value to an AV
} else {
croak("sv_rv isn t a reference to an array!");
}
CAUTION Always check your RVs with SvROK and SvTYPE before casting
them. It's all too common for C modules to crash when passed a normal
scalar where they were expecting a reference. It's much nicer to print an
error message!
Memory Management
So far I've ignored memory management. As a result, most of the preceding
examples will leak memory.
6
This is because, unlike Perl, C expects you to manage
both allocation and deallocation. The Perl API offers some help in this area, and
learning to use it correctly is the key to creating C modules that don't leak memory.
Reference Counts
Perl uses an explicit reference counting garbage collector to manage memory.
This means that every object (SV, AV, HV, and so on) created by Perl has a number
associated with it called a reference count, or refcount for short. A reference count
is simply a count of the number of objects that refer to the object. When the ref
erence count of an object reaches 0, the memory used by the object is freed by the
garbage collector.
6. A piece of code is said to leak memory when it fails to deallocate memory that is no longer
being used. The classic test for memory leaks is to run a piece of code inside a loop and watch
to see if the memory used by the program grows over time.
192
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved