specifying string types in cython code
<p>I'm doing some experimentation with cython and I came across some unexpected behavior: </p>

<pre><code>In [1]: %load_ext cython

In [2]: %%cython
   ...: cdef class foo(object):
   ...:     cdef public char* val
   ...:     def __init__(self, char* val):
   ...:         self.val = val
   ...:

In [3]: f = foo('aaa')

In [4]: f.val
Out[4]: '\x01'
</code></pre>

<p>What's going on with <code>f.val</code>? repeated inspection produces seemingly random output, so it looks like <code>f.val</code> is pointing to invalid memory.</p>

<p>The answer to <a href="https://stackoverflow.com/questions/30879708/string-in-cython-functions">this question</a> suggests that you should use <code>str</code> instead.
Indeed, this version works fine:</p>

<pre><code>In [21]: %%cython
    ...: cdef class foo(object):
    ...:     cdef public str val
    ...:     def __init__(self, str val):
    ...:         self.val = val
</code></pre>

<p>So, what is going on in the first version? It seems like the <code>char*</code> is getting freed at some point after class construction but I'm not really clear on why.</p>