Python extension for Upskirt: garbage at end of string
I've been trying to make a Python extension for Upskirt. I though it would not be too hard for a first C project since there are examples (example program in the Upskirt code and the Ruby extension).
The extension works, it converts the Markdown I throw at it, but sometimes the output has some garbage at the end of the string. And I don't know what causes it.
Here's some output:
python test.py
<module 'pantyshot' from '/home/frank/Code/pantyshot/virtenv/lib/python2.7/site-packages/pantyshot.so'>
<built-in function render>
'<p>This <strong>is</strong> <em>a</em> <code>test</code>. <a href="http://example.com">Test</a>.</p>\n\x7f'
<p>This <strong>is</strong> <em>a</em> <code>test</code>. <a href="http://example.com">Test</a>.</p>
开发者_如何学JAVA--------------------------------------------------------------------------------
'<p>This <strong>is</strong> <em>a</em> <code>test</code>. <a href="http://example.com">Test</a>.</p>\n\x7f'
<p>This <strong>is</strong> <em>a</em> <code>test</code>. <a href="http://example.com">Test</a>.</p>
--------------------------------------------------------------------------------
My code can be found in my Github repo. I called it pantyshot, because I thought of that when I heard upskirt. Strange name, I know.
I hope someone can help me.
You are doing a strdup
in pantyshot_render
:
output_text = strdup(ob->data); /* ob is a "struct buf *" */
But I don't think ob->data
is a nul-terminated C string. You'll find this inside upskirt/buffer.c
:
/* bufnullterm • NUL-termination of the string array (making a C-string) */
void
bufnullterm(struct buf *buf) {
if (!buf || !buf->unit) return;
if (buf->size < buf->asize && buf->data[buf->size] == 0) return;
if (bufgrow(buf, buf->size + 1))
buf->data[buf->size] = 0; }
So, you're probably running off the end of the buffer and getting lucky by hitting a '\0'
before doing any damage. I think you're supposed to call bufnullterm(ob)
before copying ob->data
as a C string; or you could look at ob->size
, use malloc
and strncpy
to copy it, and take care of the nul-terminator by hand (but make sure you allocation ob->size + 1
bytes for your copied string).
And if you want to get rid of the newline (i.e. the trailing \n
), then you'll probably have to do some whitespace stripping by hand somewhere.
精彩评论