Commit 978640f8 authored by gabrieldemarmiesse's avatar gabrieldemarmiesse

Moved an example from memory_allocation.rst to the examples directory to be tested.

parent ff577a2b
import random
from libc.stdlib cimport malloc, free
def random_noise(int number=1):
cdef int i
# allocate number * sizeof(double) bytes of memory
cdef double *my_array = <double *> malloc(number * sizeof(double))
if not my_array:
raise MemoryError()
try:
ran = random.normalvariate
for i in range(number):
my_array[i] = ran(0, 1)
return [my_array[i] for i in range(number)]
finally:
# return the previously allocated memory to the system
free(my_array)
......@@ -32,27 +32,9 @@ in cython from ``clibc.stdlib``. Their signatures are:
void* realloc(void* ptr, size_t size)
void free(void* ptr)
A very simple example of malloc usage is the following::
A very simple example of malloc usage is the following:
import random
from libc.stdlib cimport malloc, free
def random_noise(int number=1):
cdef int i
# allocate number * sizeof(double) bytes of memory
cdef double *my_array = <double *>malloc(number * sizeof(double))
if not my_array:
raise MemoryError()
try:
ran = random.normalvariate
for i in range(number):
my_array[i] = ran(0,1)
return [ my_array[i] for i in range(number) ]
finally:
# return the previously allocated memory to the system
free(my_array)
.. literalinclude:: ../../examples/tutorial/memory_allocation/malloc.pyx
Note that the C-API functions for allocating memory on the Python heap
are generally preferred over the low-level C functions above as the
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment