Controlling writable strings

In a large number of C programs, character strings may be constant and never written to. If this is the case, every user does not need a separate copy of these strings.

You can force all strings in a given source file to be the part of the program that includes executable code and constant data by using #pragma strings(readonly) or the ROSTRING compiler option. Figure 1 illustrates one way to make the strings constant.

Figure 1 shows a sample program (CCNGRE1) that makes strings constant. The string "hello world\n" is included with the executable code because #pragma strings(readonly) is specified. This can yield a performance and storage benefit.

Figure 1. Making strings constant
/* this example demonstrates how to make strings constant */

#pragma strings(readonly)
#include <stdio.h>

int main(void)
{
   printf("hello world\n");

   return(0);
}
Ensure that you do not write to read-only strings. The following code tries to overwrite the literal string "abcd" because 'chrs' is just a pointer:
char chrs[]= "abcd";
memcpy(chrs,"ABCD",4);
Program exceptions or unpredictable program behavior may result if you attempt to write to a string constant.

The ROSTRING compiler option has the same effect as #pragma strings(readonly) in the program source. For more information, see ROSTRING | NOROSTRING in z/OS XL C/C++ User's Guide.