2

i'm pretty much new at python,I know very good C-programming When calling the follwing function in C many time it will cause an memory error:

#include <stdio.h>
#include <stdlib.h> 
    char *foo(){
        char *a=(char*)malloc(1000);
        return a;
    }
void main(){
char *A;
while(1){
    A=foo()  // Will cause memory leack Or some kind of error and crash 
    }
}

since each call for the function will allocate new memory block and when the function end it wont be free ... ending "eating" all the available memory My question: is the following Python function will cause the same when calling many times???:

    def foo():
        data=[]
        for i in range(0,1000):
            data.append(str(i))

        return data
while(1):
    data=foo()

I'm asking cause i know that "data" is a list type Object meaning it's like an array in C ... Thanks a lot!

0

3 Answers 3

2

No risk of memory exhaustion in Python with danggling memory chunks. Python uses a garbage collector that will take care of objects that are no longer referenced. So each time you assign data with the result of foo(), the previous array has no longer any reference pointing to it and will be erased by the garbage collector at some point.

Sign up to request clarification or add additional context in comments.

Comments

1

Speaking cplusplus language Python doesn't support memory leaks :) But in python world memory leak has different meaning. Let me show example:

some_dict = {}
k = 'key'
v = "value"
some_dict[k] = v

So, now some_dict contains a link to k. And if some_dict is some long-live object, python will keep v alive until some_dict dies. And if application have a lot of longlive objects that takes all memory of OS, it will receive a Memory Error after first unsuccessful allocation. If you want to receive MemoryError - just try to open some really huge file (more than your RAM+swap) in memory.

Comments

0

Actually, I think in this particular example the answer is no, because you create the list each time at the start of foo(), and python will automatically free up that memory when it detects that it is no longer referenced, which will happen at the point of assigning the next return value of foo() to the data variable in the while loop.

In C you have to code the freeing of malloc()ed memory. In python, the interpreter is allocating memory and can automatically free it up once it is no longer needed.

1 Comment

@Jimilian@Jean-Noel Avila Thanks A lot!! I'm new at Python .. I used to programer a lot in C ... Perfect answers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.