Search code examples
cpointersstrcpystring.h

unexpected result in C strcpy and strncpy combination


In practicing for final exam in my high school, we got following question:

Find values of strings s1, s2 and s3 after code executed:

char s1[] = "Short Message Service", *s2, *s3;
s2 = strchr(s1, 'M');
s3 = strrchr(s2,'S');
strncpy(s1 + 1, s2, 1);
strcpy(s1 + 2, s3);

Whole class expected result to be:

s1 = SMService
s2 = Message Service
s3 = Service

When we tested it by executing code we were surprised to see result is:

s1 = SMService
s2 = ice
s3 = Service

The problem is nobody can figure out why s2 got shortened. While trying to figure it out, I found out s2 is remaining "Message Service" until the last line of code where "strcpy" function executes. I assume the problem might be in pointer addresses but I couldn't figure out how strcpy is affecting s2.

So my question is why s2 isn't what we expected it to be and why it got shortened?


Solution

  • In your code s2 was pointing to the M in s1 and then got overwritten by s3 in your last strcpy:

    char s1[] = "Short Message Service", *s2, *s3;
    s2 = strchr(s1, 'M');   // s2 is pointing to s1 + 6 = Message Service
    s3 = strrchr(s2, 'S');  // s3 is pointing to s1 + 14 = Service 
    strncpy(s1 + 1, s2, 1); // Write M in to s1[1], s1 = SMort Message Service 
    strcpy(s1 + 2, s3);     // Write Service into s1 + 2
                            // s1 = SMService but s2 is pointing to s1 + 6 = ice