title: Custom new operation in Tensorflow results in exception 'pointer being freed was not allocated'
body: <p>I am learning how to add operation to tensorflow following <a href="https://www.tensorflow.org/versions/r0.9/how_tos/adding_an_op/index.html" rel="nofollow">Google's tutorial</a>, but run into some trouble.</p>
  
  <p>I cloned the sources from the Github, and plan to add the <code>Fact</code> operation in <code>tensorflow/core/user_ops/fact.cc</code> to the framework. Following is my approach:</p>
  
  <ol>
  <li>Create a <code>BUILD</code> file in <code>tensorflow/core/user_ops/</code>, with the content:</li>
  </ol>
  
  <blockquote>
  <pre><code>load("//tensorflow:tensorflow.bzl", "tf_custom_op_library")
  
  tf_custom_op_library(
      name = "fact.so",
      srcs = ["fact.cc"]
  )
  </code></pre>
  </blockquote>
  
  <ol start="2">
  <li>Run following command in the root directory of the cloned project:</li>
  </ol>
  
  <blockquote>
    <p>bazel build -c opt -s //tensorflow/core/user_ops:fact.so</p>
  </blockquote>
  
  <p>This does create a <code>fact.so</code> file in <code>bazel-bin/tensorflow/core/user_ops/</code></p>
  
  <ol start="3">
  <li><p>Copy the generated <code>fact.so</code> to my Python project, which is located is another irrelevant place.</p></li>
  <li><p>In the Python project, run</p></li>
  </ol>
  
  <blockquote>
  <pre><code>import tensorflow as tf
  
  fact_module = tf.load_op_library('fact.so')
  with tf.Session(''):
    print(fact_module.fact2().eval())
  </code></pre>
  </blockquote>
  
  <p>The result is an exception:</p>
  
  <blockquote>
    <p>python(77790,0x7fff742f7000) malloc: <strong>* error for object
    0x1c890ffde89: pointer being freed was not allocated
    *</strong> set a breakpoint in malloc_error_break to debug Abort trap: 6</p>
  </blockquote>
  
  <p>However, if I build the operation directly using clang++ like:</p>
  
  <blockquote>
    <p>clang++ -std=c++11 -shared tensorflow/core/user_ops/fact.cc -o
    ~/Desktop/fact.so -fPIC -I $TF_INC -undefined dynamic_lookup</p>
  </blockquote>
  
  <p>where $TF_INC is computed by </p>
  
  <blockquote>
    <p>TF_INC=$(python -c 'import tensorflow as tf;
    print(tf.sysconfig.get_include())')</p>
  </blockquote>
  
  <p>everything works fine.</p>
  
  <p>Could anyone tell my why the first approach failed?</p>