gcc<->gpc: reallocating and disposing buffers

Frank Heckenbach frank at g-n-u.de
Wed Aug 29 03:54:25 CEST 2001

Sorry for the late reply ...

George Shapovalov wrote:

> I am sorry for somewhat lengthy email, I tried to get most of the details
> here.  I could not find detailed discussion of this topic in documentation, 
> so this is a short investigation.
> 	First some description: I need to implement access to some data stored in 
> special binary format for reading which large chunks of C code exist. On the 
> other hand it would be easier/cleaner to do data processing  in pascal (It is 
> really nice to use schemata for some purposes). So I thought to create some c 
> functionds which would access data and pass it to pascal program.
> It would be nice to have c functions allocate and fill buffers and then have 
> pascal code dispose them after processing. So I tried to test what happens.
> Below is the model code which is supposed to represent such situation. In 
> fact it tests passage of buffers in both ways:
> I allocate small array on pascal side, pass it to c, then reallocate it there 
> (slightly larger block) - actually I use free and then malloc, but realloc 
> gave the same result. Then upon return to pascal I dispose the buffer.
> 	To tell the truth I did not expect things to work at all, but it appears 
> that they do work - one way only. Unfortunately the opposite way to what I 
> need.

In general, you can indeed expect it to work both ways.

There's only one catch: If the program ever uses Mark/Release (or
something which uses them itself such as the HeapMon unit), you
cannot free pointers in C that were allocated in Pascal. But since
you don't use Mark/Release, that's not relevant here.

Unfortunately, your example contains a fe problems:

- cmem.c is missing. I added for it:
  #include <stdlib.h>
  void cfree (void *p) { free (p); }

- cFunc does not return a value, and the Pascal code treats the
  function as a procedure.

- The pointer in Pascal is declared as fixed-size, so even after the
  reallocation, Pascal treats its size as 10 chars and writes it

- The C statemtent `*x="0123456789abcde"' assigns a *pointer* rather
  than copying an array. So you try, in the end, to free a C string
  constant which obviously may crash (regardless whether you do that
  in Pascal or C).

So, the problem here is a misunderstanding of C's pointer/array
semantics (and therefore a little OT ;-). I don't know if that's the
problem you had in your real code, but if there's something else for
which GPC may be to blame, let us know.


Frank Heckenbach, frank at g-n-u.de, http://fjf.gnu.de/
GPC To-Do list, latest features, fixed bugs:

More information about the Gpc mailing list