Reputation: 1
I have to write a buggy server that will crash due to off by one error. My doubt is why the below code gives a segmenation fault
char wbuff[5];
char abuff[5]= "12345";
strcpy(wbuff,abuff);
but below code doesn't
char buf[BUFSIZE];
char wbuf[5];
n = read(connfd, buf, BUFSIZE); // read input string from client
strcpy(wbuf,buf); // strlen(buf) is greater than 5
Upvotes: 0
Views: 69
Reputation: 5060
Exceed of array's size is undefined behaviour. Something can happen. If you don't have SIGSEGV now, you can get it later in program run.
Upvotes: 0
Reputation: 15511
The first one copies from a non-null-terminated string (abuff) to the other string. So it walks off the end of abuff until it finds a zero byte, which could be quite a ways, and causes a segfault. The other one copies from a properly-terminated string (buf) to the undersized string wbuf, and stops copying after it copies strlen(buf)+1 bytes. So the first is more likely to cause a segfault, but both are errors.
Upvotes: 1