473,651 Members | 2,644 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C extension question about avoiding memory leaks with the object returned...

I wrote some C functions and successfully imported them into Python.

All is apparently well but there is one question about the object returned
by the C function that is bugging me...

Take for example this last line of a C extension:

return Py_BuildValue(" s", my_string);
If my_string allocated dynamically:
=============== ===========
Will Python successfully handle garbage collection of my_string?
Will there be any problems because it was built within my C function?

(I would think Python will successfully receive a COPY of my_string
but that the original my_string object will be a memory leak!!!)

If my_string allocated statically:
=============== ===========
Don't all statically declared objects get killed when you exit a C function?
This is not a problem because Python will get a COPY right?

(This seems "safer" until my dynamic question above gets answered but
with static guys you lose flexibility with the SIZE of the string of course.)

Any help would be greatly appreciated.

Chris
Jul 18 '05 #1
4 2354
se******@spawar .navy.mil (Christian Seberino) writes:
return Py_BuildValue(" s", my_string);
In this case, Py_BuildValue is very expensive. Use PyString_FromSt ring
instead.
If my_string allocated dynamically:
=============== ===========
Will Python successfully handle garbage collection of my_string?
No. The resulting Python string object will be a copy; the original
string is considered read-only, and no attempt to release it is made.
Will there be any problems because it was built within my C function?
If you don't release it, there will be a memory leak. Apart from that:
no.
If my_string allocated statically:
=============== ===========
Don't all statically declared objects get killed when you exit a C function?
You might need to explain what a statically declared string is, in
C. If you are talking about string literals: no, they don't get killed
when a C function exits. They exist from the start of the program
until it ends.
This is not a problem because Python will get a COPY right?


Right.

Regards,
Martin
Jul 18 '05 #2
Christian Seberino wrote:
return Py_BuildValue(" s", my_string);
If my_string allocated dynamically:
=============== ===========
Will Python successfully handle garbage collection of my_string?
Nope. It's your string, you handle it.
Will there be any problems because it was built within my C function?
No problems.
(I would think Python will successfully receive a COPY of my_string
but that the original my_string object will be a memory leak!!!)
Agreed.

So don't do that. Instead write (untested):

PyObject* ret = Py_BuildValue(" s", my_string);
free(my_string) ;
return ret;
If my_string allocated statically:
=============== ===========
Don't all statically declared objects get killed when you exit a C
function? This is not a problem because Python will get a COPY right?
Rigth.
AFAIUC, static objects "get killed" along with your whole program.
Probably you are talking about function local objects (dynamically)
allocated in stack.
(This seems "safer" until my dynamic question above gets answered but
with static guys you lose flexibility with the SIZE of the string of
course.)


"All what you're doing is safe as long as you understand what are you doing"
(c) not me

HTH,
Mike


Jul 18 '05 #3
Martin

Thanks. Is there no way to return a dynamically allocated C string in your
C extension without making a memory leak? Must all strings be allocated to be
a fixed size at compile time like this...???

#define MAX_LENGTH 20
....
char my_string[MAX_LENGTH];
....
return Py_BuildValue(" s", my_string);

(This is what I meant by "statically allocated string".)

Will *this* make a memory leak as well?

Chris

ma****@v.loewis .de (Martin v. Löwis) wrote in message news:<m3******* *****@mira.info rmatik.hu-berlin.de>...
se******@spawar .navy.mil (Christian Seberino) writes:
return Py_BuildValue(" s", my_string);


In this case, Py_BuildValue is very expensive. Use PyString_FromSt ring
instead.
If my_string allocated dynamically:
=============== ===========
Will Python successfully handle garbage collection of my_string?


No. The resulting Python string object will be a copy; the original
string is considered read-only, and no attempt to release it is made.
Will there be any problems because it was built within my C function?


If you don't release it, there will be a memory leak. Apart from that:
no.
If my_string allocated statically:
=============== ===========
Don't all statically declared objects get killed when you exit a C function?


You might need to explain what a statically declared string is, in
C. If you are talking about string literals: no, they don't get killed
when a C function exits. They exist from the start of the program
until it ends.
This is not a problem because Python will get a COPY right?


Right.

Regards,
Martin

Jul 18 '05 #4
se******@spawar .navy.mil (Christian Seberino) writes:
Thanks. Is there no way to return a dynamically allocated C string
in your C extension without making a memory leak? Must all strings
be allocated to be a fixed size at compile time like this...???
No. You will need to release the dynamically allocated string, after
calling PyString_FromSt ring. How precisely to do that depends on how
precisely it was allocated, but assuming it was allocated with
malloc(3), you should release it with free(3).
#define MAX_LENGTH 20
...
char my_string[MAX_LENGTH];
...
return Py_BuildValue(" s", my_string);

(This is what I meant by "statically allocated string".)

Will *this* make a memory leak as well?


No.

Regards,
Martin
Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2318
by: Spur | last post by:
Hi all, I implemented a memory allocation/deallocation class that logs all new/delete calls (overloaded) and remembers for each allocated block where it was allocated from (using a macro that passes __FILE__ and __LINE__). On destruction, it reports all undeleted blocks (memory leaks). The class is implemented in a separate .h/.cpp pair, and should be linked to
4
2942
by: Daniel | last post by:
I need to build the maze board(like 2d array) using a tree. But I find that my buildTree function doesn't work. Could anyone give me some hints on debugging it? Thanks bool BuildTree(TreeNodePtr *T, int x, int y) { if (boardSize == 0) //boardSize is a global variable { return TRUE; } else {
10
2767
by: s.subbarayan | last post by:
Dear all, I happen to come across this exciting inspiring article regarding memory leaks in this website: http://www.embedded.com/story/OEG20020222S0026 In this article the author mentions: "At a certain point in the code you may be unsure if a particular block is no longer needed. If you free() this piece of memory, but continue to access it (probably via a second pointer to the same
0
3899
by: Frank Lopez | last post by:
Does anyone know if Microsoft generated a whitepaper on this topic? Does anyone know what the solution is? (meaning, eliminate the leak problem -- I am seeing three memory leaks from dllmodul.cpp(102) similar to what is mentioned below)... I am calling MFC as part of unmanaged code used by the managed code. +--------
15
2790
by: Chetan Raj | last post by:
Hi All, We have a web-application in asp.net that interacts with legacy code written in COM. The memory usage in aspnet_wp.exe increases every sec and never reduces. Using the .NET performance counters, we found that unmanaged memory was 90% of the total private bytes of aspnet_wp.exe. We suspected that the COM code has memory leaks. So we made it as a COM+ Service running as dllhost.exe. Surprisingly, there was no memory increase in...
15
8305
by: cedgington | last post by:
I wanted to take advantage of the large set of functionality offered by the framework, so for my latest project I'm using managed C++ with .NET v2. I'm using the gcnew operator in two different ways, and I'm confused about the lifetime of objects and whether or not I should be calling delete. Here are two examples: ref class SYMBOL : public IComparable { public: // Constructor / destructor
11
3943
by: seberino | last post by:
Suppose a C extension locally built an array of PyObject* 's as follows... my_array = malloc(n * sizeof(PyObject*)); for (i = 0; i < n; i++) { my_array = PyList_New(0); } Q1: Must I do a Py_DECREF(my_array) on all elements before exiting this C extension function? (What if
2
4884
by: =?Utf-8?B?Tm9tYW4gQWxp?= | last post by:
Hi, We are facing a strange problem in our ASP. NET website. Some times it gives the following unhandled exception. Error Message: Exception of type System.Web.HttpUnhandledException was thrown. Detailed Error Message: System.InvalidOperationException: There has been an overflow or underflow in GC memory pressure. The possible cause is unbalanced AddMemoryPressure and RemoveMemoryPressure calls. at...
2
1233
by: Oltmans | last post by:
Hi all, I'm stuck in a situation where I need help. Any help will be highly appreciated. I've created an object, after creating the object, I'm assigning one of its functions to an event handler i.e. to onBlur event of Text-area. Problem is that when I try to access object properties from the handler function, I cannot access them in some cases and get a value of undefined. Here is the sample code that I'm trying
0
8349
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8275
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8695
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8460
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7296
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4281
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2696
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1906
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1585
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.