title: Create copy of PostgreSQL internal C function and load it as user defined function
body: <p>I would like to create modified version of C function <code>int2_avg_accum</code> located in <code>src/backend/utils/adt/numeric.c</code>. I thought I can (as a start) just compile <code>numeric.h</code> and load <code>int2_avg_accum</code> as user defined function.</p>
  
  <p>What I did:</p>
  
  <ol>
  <li>Added <code>PG_MODULE_MAGIC</code> to <code>numeric.h</code> (as described <a href="http://www.postgresql.org/docs/current/static/xfunc-c.html" rel="nofollow">here</a>)</li>
  <li>Renamed <code>int2_avg_accum</code> to <code>int2_avg_accum2</code> in <code>numeric.h</code></li>
  <li>Compiled <code>numeric.h</code> as described in the documentation (no errors, no warnings) (<code>cc -fpic -I</code>pg_config --includedir-server<code>-c numeric.c</code> and then <code>cc -shared -o numeric.so numeric.o</code>)</li>
  <li>Created a function in PostgreSQL:</li>
  </ol>
  
  <p>.</p>
  
  <pre><code>create or replace function int2_avg_accum2(bigint[], smallint)
    returns bigint[] as
  '/usr/lib/postgresql/9.1/lib/numeric', 'int2_avg_accum2'
    language c
    cost 1;
  alter function int2_avg_accum2(bigint[], smallint)
    owner to postgres;
  </code></pre>
  
  <p>When I try to run <code>select int2_avg_accum2(array[1::bigint,1],1::smallint);</code> I get only message (in pgAdmin): "Do you want to attempt to reconnect to the database?". No other messages or errors. </p>
  
  <p>When I call the function I see the following in <code>/var/log/postgresql/postgresql-9.1-main.log</code>:</p>
  
  <pre><code>2013-12-03 09:52:02 CET LOG:  server process (PID 3366) was terminated by signal 11: Segmentation fault
  2013-12-03 09:52:02 CET LOG:  terminating any other active server processes
  2013-12-03 09:52:02 CET WARNING:  terminating connection because of crash of another server process
  2013-12-03 09:52:02 CET DETAIL:  The postmaster has commanded this server process to roll back the current transaction and exit, because another server process exited abnormally and possibly corrupted shared memory.
  2013-12-03 09:52:02 CET HINT:  In a moment you should be able to reconnect to the database and repeat your command.
  2013-12-03 09:52:02 CET LOG:  all server processes terminated; reinitializing
  2013-12-03 09:52:02 CET LOG:  database system was interrupted; last known up at 2013-12-03 09:50:53 CET
  2013-12-03 09:52:02 CET LOG:  database system was not properly shut down; automatic recovery in progress
  2013-12-03 09:52:02 CET LOG:  record with zero length at 0/B483EA0
  2013-12-03 09:52:02 CET LOG:  redo is not required
  2013-12-03 09:52:03 CET LOG:  autovacuum launcher started
  2013-12-03 09:52:03 CET LOG:  database system is ready to accept connections
  </code></pre>
  
  <p>What I have to do differently in order to get working copy of <code>int2_avg_accum</code>?</p>