My simple C program is as follows. Initially, I've defined variable buf1
with 3 char.
I don't have any problem with 2 char such as AB
or XY
user@linux:~/c# cat buff.c; gcc buff.c -o buff; echo -e '\n'; ./buff
#include <stdio.h>
#include <string.h>
int main() {
char buf1[3] = "AB";
printf("buf1 val: %s\n", buf1);
printf("buf1 addr: %p\n", &buf1);
strcpy(buf1,"XY");
printf("buf1 val: %s\n", buf1);
}
buf1 val: AB
buf1 addr: 0xbfe0168d
buf1 val: XY
user@linux:~/c#
Unfortunately, when I add 3 char such as XYZ
, I'm getting the following error message when compiling the program.
buff.c:8:2: warning: ‘__builtin_memcpy’ writing 4 bytes into a region of size 3 overflows the destination [-Wstringop-overflow=]
strcpy(buf1,"XYZ");
Isn't XYZ
considered as 3 bytes? Why does the error message said 4 bytes
instead of 3 bytes
user@linux:~/c# cat buff.c; gcc buff.c -o buff; echo -e '\n'; ./buff
#include <stdio.h>
#include <string.h>
int main() {
char buf1[3] = "AB";
printf("buf1 val: %s\n", buf1);
printf("buf1 addr: %p\n", &buf1);
strcpy(buf1,"XYZ");
printf("buf1 val: %s\n", buf1);
}buff.c: In function ‘main’:
buff.c:8:2: warning: ‘__builtin_memcpy’ writing 4 bytes into a region of size 3 overflows the destination [-Wstringop-overflow=]
strcpy(buf1,"XYZ");
^~~~~~~~~~~~~~~~~~
buf1 val: AB
buf1 addr: 0xbfdb34fd
buf1 val: XYZ
Segmentation fault
user@linux:~/c#