Unexpected Behavior In ANSI C String Manipulation Functions, With Overlapping Strings (Doc ID 1336061.1)

Last updated on AUGUST 03, 2016

Applies to:

Solaris Operating System - Version 8 6/00 U1 to 11.2 [Release 8.0 to 11.0]
Oracle Solaris Studio - Version Forte Developer 6 Update 2 to 12.4 [Release 6.0 to 12]
Information in this document applies to any platform.

Symptoms

Some standard library functions from libc which copy, append, or modify strings show unexpected behavior when source string and destination string overlap.

Example:

% cat strcpy_test.c
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
   {
   char s[20]="0123456789abcdef";
   char t[25]="0123456789abcd";
   int i;

   for (i=0;i<4;i++) {

      /* Overlapping strings. UNDEFINED BEHAVIOR per
         section 7.21.2.3 The strcpy function
         of the ANSI C standard. */
      strcpy(s,s+1);
      strcpy(t+1,t);

      printf ("Lets see what happens in s: %s\n",s);
      printf ("Lets see what happens in t: %s\n",t);
   }

   return 0;
   }
% cc -V -m64 strcpy_test.c
cc: Sun C 5.11 SunOS_i386 2010/08/13
acomp: Sun C 5.11 SunOS_i386 2010/08/13
ld: Software Generation Utilities - Solaris Link Editors: 5.10-1.500
% ./a.out
Lets see what happens in s: 123456789abcdef
Lets see what happens in t: 00123456679abcd
Lets see what happens in s: 23456789abcdef
Lets see what happens in t: 000123456679abcd
Lets see what happens in s: 345678aabcdef
Lets see what happens in t: 0000123455679abcdd
Lets see what happens in s: 45678abbcdef
Lets see what happens in t: 00000123445679abcccd

Changes

The issue is more likely to occur for 64-bit applications than for 32-bit applications.

The issue is more likely to occur on 64-bit applications on Solaris on x86-64


The issue is more likely to occur if the offset between the overlapping strings is small.

In many implementations, including the Solaris libc implementation, the issue is more likely to occur when the destination string starts at or after the beginning of the source string, rather than before the beginning of the source string.

Cause

Sign In with your My Oracle Support account

Don't have a My Oracle Support account? Click to get started

My Oracle Support provides customers with access to over a
Million Knowledge Articles and hundreds of Community platforms