amazing memcpy bug on Solaris

Russ Allbery rra@stanford.edu
Fri Oct 1 00:00:00 GMT 1999


[ Posted and mailed. ]

mhalibard <mhalibard@csafe.com> writes:

> // this one crashes on memcpy with segmentation fault 
> void main()
> {
> 	char* buffer_ptr = "abcdefghijklmnop";
> 	long * outBuff = (long *)malloc(4);
> 	memcpy(buffer_ptr, outBuff, 1); 
> }

The GCC info pages contain:

Incompatibilities of GCC
========================

   There are several noteworthy incompatibilities between GNU C and most
existing (non-ANSI) versions of C.  The `-traditional' option
eliminates many of these incompatibilities, *but not all*, by telling
GNU C to behave like the other C compilers.

   * GCC normally makes string constants read-only.  If several
     identical-looking string constants are used, GCC stores only one
     copy of the string.

     One consequence is that you cannot call `mktemp' with a string
     constant argument.  The function `mktemp' always alters the string
     its argument points to.

     Another consequence is that `sscanf' does not work on some systems
     when passed a string constant as its format control string or
     input.  This is because `sscanf' incorrectly tries to write into
     the string constant.  Likewise `fscanf' and `scanf'.

     The best solution to these problems is to change the program to use
     `char'-array variables with initialization strings for these
     purposes instead of string constants.  But if this is not possible,
     you can use the `-fwritable-strings' flag, which directs GCC to
     handle string constants the same way most C compilers do.
     `-traditional' also has this effect, among others.

If you initialize a variable with a constant string, gcc assumes that you
really want that string to be *constant* and loads it into read-only
memory.

-- 
Russ Allbery (rra@stanford.edu)         <URL: http://www.eyrie.org/~eagle/ >


More information about the Gcc-help mailing list