Is there a need to deallocate memory after PyArg_ParseTuple

This is the place for queries that don't fit in any of the other categories.

Is there a need to deallocate memory after PyArg_ParseTuple

Postby guyafe » Tue May 21, 2013 7:46 am

Hi,
I am new at Python and getting confused in memory management of C++ and Python:
I have the following code:
Code: Select all
PyObject *pData = ...
const char *name = NULL;
PyArg_ParseTuple(pData, const_cast<char *>("s"), &name);
.
.
.

My question is how is how is the memory for name is allocated and deallocated?
Do I need to free name after I am finishing using it?
guyafe
 
Posts: 1
Joined: Tue May 21, 2013 7:38 am

Re: Is there a need to deallocate memory after PyArg_ParseTu

Postby Kebap » Tue May 21, 2013 12:12 pm

I don't know much C++ but in general, in Python, you do not have to worry about memory allocation at all. Python will gladly handle it for you. Your python looks a bit C-ish to me, but maybe it's only because of the brevity. Make sure to use the differences between the languages, not try to code C with python. :mrgreen:
Learn: How To Ask Questions The Smart Way
Join the #python-forum IRC channel on irc.freenode.net and chat with uns directly!
Kebap
 
Posts: 365
Joined: Thu Apr 04, 2013 1:17 pm
Location: Germany, Europe

Re: Is there a need to deallocate memory after PyArg_ParseTu

Postby setrofim » Tue May 21, 2013 1:16 pm

From the docs for the "s" format argument:
Python docs wrote:"s" (string) [char *]
Convert a Python string to a C pointer to a character string. You must not provide storage for the string itself; a pointer to an existing string is stored into the character pointer variable whose address you pass. The C string is null-terminated. The Python string must not contain embedded null bytes; if it does, a TypeError exception is raised.

(emphasis added). I.e. the pointer get's set to an existing string object, so you don't need to worry about its dealocation.

Every Python string has a PyStringObject struct underpining it (and the struct contains a pointer to the actual char array that is the string in memory). From quick look at Python source (and I'm no expert, so hopefully someone will correct me if I'm misreading it), it looks like "s" format eventually results in a call to PyString_TO_STRING macro that just returns the pointer to char array in PyStringObject instance:
Code: Select all
#define PyString_AS_STRING(op) (((PyStringObject *)(op))->ob_sval)

So basically, it looks like you're getting a pointer to the char array that is managed by the reference-counted PyObject that is the Python string. So allocation and deallocation of that memory is managed by the Python string object.

See this for more details on Python string implementation.
setrofim
 
Posts: 288
Joined: Mon Mar 04, 2013 7:52 pm


Return to General Coding Help

Who is online

Users browsing this forum: ac.smith, metulburr and 3 guests