在函数中从结构体间接调用指针时,指针是否会被释放?

问题描述 投票:0回答:1

假设我们在 Cython 中有以下内容:

ctypedef struct Structure:
    int* array
    int size


cdef print_fx(Structure obj):
    print(obj.array[0])

cdef create_object(int size):
    cdef Structure result
    result.size = size
    result.array = <int*>malloc(size*sizeof(int))
    for i in range(size):
        result.array[i] = 1
    return result

我想使用

print_fx
而不显式创建特定对象:

print_fx(create_object(3))

如果我写:

cdef Structure testobj = create_object(3)
print_fx(testobj)

free(testobj.array)

我必须释放结构中的指针。

如果我直接使用它,

print_fx(create_object(3))
,Jupyter中的Cell运行后它会自动释放吗?

python pointers cython
1个回答
0
投票

不,不会。您始终必须手动释放分配的内存,否则会导致内存泄漏,您的程序或计算机最终将崩溃。

%load_ext Cython

%%cython
from libc.stdlib cimport malloc, free
cdef struct teststruct:
    int * array
    int size

cdef teststruct create_object(int size):
    cdef teststruct result
    cdef int i
    result.size = size
    result.array = <int *> malloc(size * sizeof(int))
    for i in range(size):
        result.array[i] = 1
    return result

lm = 100000

def outer_func_1():
    cdef teststruct testobj = create_object(lm)
    i = testobj.array[0]
    free(testobj.array)

def outer_func_2():
    i = create_object(lm).array[0]

for i in range(1000000):
    outer_func_1() #will never crash no matter how many times it repeated

for i in range(100000):
    outer_func_2() #crashed
© www.soinside.com 2019 - 2024. All rights reserved.