title: python3 stack smashing - python extending with c
body: <p>I am writing a python extension in C. There is a library for a raspberry hw dev board in C so I'm using that. So I'm exporting a function from C to python and at the end of the call, python falls over saying <code>*** stack smashing detected ***: python3 terminated</code>.</p>
  
  <p>python call:</p>
  
  <pre><code>print("self.handle="+str(self.handle))
  ret=dcc.dcc_send(self.handle, d[0], d[1], d[2], d[3], d[4], d[5])
  print("returned: "+str(ret)) # never gets here
  </code></pre>
  
  <p>C python export (finishes):</p>
  
  <pre><code>static PyObject* dcc_send(PyObject* self, PyObject* args) {
      unsigned char handle, count, b1, b2, b3, b4, b5;
  
      if (!PyArg_ParseTuple(args, "iiiiiii", &amp;handle, &amp;count, &amp;b1, &amp;b2, &amp;b3, &amp;b4, &amp;b5))
              return NULL;
  
      printf("1234-handle: %d\n", handle);
  
      int ret = -1;
      ret = send_command(handle, count, b1, b2, b3, b4, b5);
  
      printf("1235-after-send_command-return: %d\n", ret);
  
      //Py_RETURN_NONE;
      return Py_BuildValue("i", ret);
  }
  </code></pre>
  
  <p>Another call in the stack:</p>
  
  <pre><code>int send_command(int handle, unsigned char count, unsigned char b1, unsigned char b2, unsigned char b3, unsigned char b4, unsigned char b5) {
      unsigned char message[10];
      message[0] = CMD_START_VAL;
      message[1] = CMD_DCC_MESS;
      message[2] = 0;
      message[3] = 0xF0 | count; //2 byte size
      message[4] = b1;
      message[5] = b2;
      message[6] = b3;
      message[7] = b4;
      message[8] = b5;
      message[9] = CMD_STOP_VAL;
      return write_uart(handle, message,10);
  }
  </code></pre>
  
  <p>Final call in the stack (I didn't write that completely, I just took it from the lib and fixed a few things in it like invalid memory access that used to be there):</p>
  
  <pre><code>int write_uart(int handle, unsigned char *data,int bytes) {
      #ifdef TEST
      int length = bytes;
      printf("handle: %d\n", handle);
      printf("bytes: %d\ndata: ", length);
      for (int i=0; i&lt;length; ++i)
          printf("%d ", (int) data[i]);
      printf("\n---\n");
      #endif
      int txed;
      int offset=0;
      while (length) {
          txed = write(handle, (unsigned char*)data+offset, length);
          if (txed==-1) {
              fprintf(stderr,"UART WRITE ERRROR!!\n");
              return 0;
          }
          length -= txed;
          offset += txed;
      }
      tcdrain(handle);
      return 1;
  }
  </code></pre>
  
  <p>When I run it, I get this:</p>
  
  <pre><code>self.handle=3
  1234-handle: 3
  handle: 3
  bytes: 10
  data: 160 25 0 242 47 130 0 0 0 80
  ---
  1235-after-send_command-return: 1
  *** stack smashing detected ***: python3 terminated
  Aborted
  </code></pre>
  
  <p>What am I doing wrong? Thanks</p>