Oreols - 1 year ago 71
C Question

# Unexpected behaviour with strcpy and arrays

I am writing a simple string substitution function and I have a quite interesting error. Shouldn't strcpy just overwrite the buf\streamBuf value? How come it concatenates arrays?

``````int main()
{
char buf[512];
strcpy(buf, "Test\nInput\nHere\n");

char fromCh[2] = "\n";
char toCh[4] = "\\n ";
stripChars(buf, fromCh, toCh);
printf("Here's your buf: %s", buf);
return 0;
}

void stripChars(char *streamBuf, char* fromCh, char *toCh){
char strTemp[512];
int i=0;
int iLenFrom = strlen (fromCh);
int iLenTo = strlen (toCh);
while (*streamBuf)
{
if (strncmp (streamBuf, fromCh, iLenFrom) == 0)
{
strncpy (&(strTemp[i]), toCh, iLenTo);
i += iLenTo;
streamBuf += iLenFrom;
}
else
{
strTemp[i++] = *streamBuf;
streamBuf++;
}
}
strTemp[i] = '\0';
strcpy(streamBuf, strTemp);

printf("Here's your strTemp: %s \n", strTemp);
printf("Here's your streamBuf: %s \n", streamBuf);
}
``````

and here's my output

``````Here's your strTemp: Test\n Input\n Here\n
Here's your streamBuf: Test\n Input\n Here\n
Here's your buf: Test
Input
Here
Test\n Input\n Here\n
Process finished with exit code 0
``````

Answer Source

How come it concatenates arrays?

That's because you are changing where `streamBuf` points to in the function.

Keep track of the original location of where `streamBuf` points to and use it at the end of the function.

``````void stripChars(char *streamBuf, char* fromCh, char *toCh)
{
char* originalPointer = streamBuf;

...

streamBuf = originalPointer;
strcpy(streamBuf, strTemp);

printf("Here's your strTemp: %s \n", strTemp);
printf("Here's your streamBuf: %s \n", streamBuf);
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download