[Tutor] calloc
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Thu Jan 12 03:24:14 CET 2006
On Thu, 12 Jan 2006, Burge Kurt wrote:
> How can I use calloc in python ? Before computing and processing my data
> I want to know how many bytes are available?
Hi Burge,
There's no concept of manual memory allocation in Python, and we don't
have direct access to calloc/malloc/free.
You're asking a lot of C-ish questions: have you looked through the Python
Tutorial to get aquainted with the language yet? See:
http://www.python.org/doc/tut/
One of the main distinctions between Python and C is that Python
programming has a very dynamic feel to it. Program properties that may be
static in other languages are fairly dynamic in Python.
For example, rather than predefine a line buffer to read lines from a
file, we use the readline() method of a file, which itself dynamically
expands if the line is very long.
The small program:
######
file = open("/etc/passwd")
for line in file:
print line
######
does what you might expect: it displays every line in the file. Note here
that there are no hardcoded places where we've defined how long line must
be. (An equivalent C program would be slightly more difficult to write
unless we changed its semantics to read the file character-by-character or
block-by-block where each unit is the same size, rather than line-by-line
where each line's length can vary.)
All the memory allocation and deallocation is handed by the Python
runtime. Regions of memory that no longer are reachable are freed by
garbage collection (or reference counting). This GC scheme reduces the
chance of making silly memory-related errors such as double-free or memory
leaking.
More information about the Tutor
mailing list