Returning char* from C routines in Visual COBOL under Unix

[Migrated content. Thread originally posted on 03 February 2012]


I found that when I perform two calls to a C program, and the second string returned by C is smaller than the first one, COBOL does not recognize the 0x0 character and shows the two strings overlapped.

For example:

The first call returns 'file11111.txt', and the second 'file2.txt'. Then COBOL understands 'file2.txt txt'.

Dump of p_szFile in C program ='file11111.txt'                                 
66 69 6C 65 31 31 31 31 31 2E 74 78 74                                         
FILE-W IN COBOL=file11111.txt

Dump of p_szFile in C program ='file2.txt'                                     
66 69 6C 65 32 2E 74 78 74                                                     
FILE-W IN COBOL=file2.txt txt
  • Verified Answer

    This is to be expected as a NULL terminated string is a C construct and not a COBOL one.

    In COBOL a PIC X data item can contain any character including a X"00" (NULL).

    In order to get the expected results in COBOL you should either initialize the field to spaces before calling the C program or extract the data from the field after the call using something like:

        unstring p_szFile delimited by x"00"
           into p_szFile

    This has the effect of removing the NULL byte and anything following it.

    Note: NULL-terminated strings are supported in COBOL when specifying a Z"literal".
    MOVE Z"123" to field1 would result in the value "123" followed by a X"00" being moved into field1.