I'm learning string functions in C and I can't seem to get my teacher's demo using strcpy()
to remove white spaces to work on my machine while it works perfectly fine for him. Here's the source code:
#include <stdio.h>
#include <string.h>
int main()
{
char s[20]="abc def ghi";
char *ptr = strstr(s, " ");
while(ptr!=NULL)
{
printf("Before trim: %s\n", s);
strcpy(ptr, ptr+1);
printf("After trim : %s\n", s);
printf("\n");
ptr = strstr(s, " ");
}
return 0;
}
Expected result:
Before trim: abc def ghi
After trim : abc def ghi
Before trim: abc def ghi
After trim : abc def ghi
Before trim: abc def ghi
After trim : abc def ghi
Before trim: abc def ghi
After trim : abc def ghi
Actual result:
Before trim: abc def ghi
After trim : abc def ghi
Before trim: abc def ghi
After trim : abc def ghi
Before trim: abc def ghi
After trim : abc def hhi
Before trim: abc def hhi
After trim : abc def hii
I've searched for this error and learned that strcpy()
is unsafe because it may cause overflow or undefined behavior. Most of the search I've read is about the destination buffer is not large enough. I don't know the keyword of this strange behavior. Can someone please explain to me what am I doing wrong? Thank you in advance!