I have a loop that looks something like this
while(condition){
read_some_data(source, buf, BUFSIZE);
printf(buf);
memset(buf, 0, BUFSIZE+1);
//do stuff to affect condition that does not touch buf
}
buf is an char array of size BUFSIZE+1. The strange thing is that if I comment out the printf, the program executes perfectly with no segmentation fault. It is only when I try to print out buf that I get the problem. Also, the seg fault does not necessarily happen on the first iteration of the loop. It usually takes 6 or 7 iterations.
Also, there is no dynamic memory allocation in this program.
bufhas a null (zero-valued) byte somewhere within the allocated range. That null byte is howprintfcan tell that it’s reached the end of a string; without it, it will keep reading past where it can safely do so.bufdoesn’t contain anything like%dthatprintfmight take to indicate additional arguments. Better yet — just useprintf("%s", buf), which completely eliminates any such risk.