remykits
remykits

Reputation: 1775

Does python free the memory if I delete a string reference?

Python will keep the space alloced for int value even though the int value has been delete, showing as follows:

age = 9999
del age

the memory stored variable age will be used to store other int value, as a result, the free function will never be called for this memory, but I don't know does string object use the same strategy to manage memory? I mean the memory alloc for string will never be freed.

for why python will never free memory for int object, please read this blog: http://www.laurentluce.com/posts/python-integer-objects-implementation/

python will manage a free_list(python-2.7.3 source code:intobject.c line:45) to hold every memory alloc for a int object and will never dealloc it

Upvotes: 1

Views: 1706

Answers (2)

Winston Ewert
Winston Ewert

Reputation: 45039

If you take a look at the python string implementation you'll find the releavent line:

op = (PyStringObject *)PyObject_MALLOC(sizeof(PyStringObject) + size);

Which shows that strings are simply allocated using python's malloc. They don't use pools like integers because python strings objects vary in size depending on the length of the string. So you couldn't use a pool in the same way you do for integers.

See: http://www6.uniovi.es/python/dev/src/c/html/stringobject_8c-source.html

Upvotes: 2

Ned Batchelder
Ned Batchelder

Reputation: 375584

Python manages all memory for you. If a value is referenced by a name, it will remain in memory. Once a value is no longer referenced by any names, the interpreter is free to reclaim the memory. You don't have to worry about this.

I don't understand your example, or why you think the memory used by "age" will be used over again. Keep in mind, Python names are not like C variables: they don't represent allocated memory. They are labels that can refer to values.

Upvotes: 5

Related Questions