Sometimes we put some debug prints in our code this way
printf("successfully reached at debug-point 1\n");
some code is here
printf("successfully reached at debug-point 2");
After the last printf
a segmentation fault occurs.
Now in this condition only debug-point1 will be print on stdio debug-point 2 print was written to stdio buffer but its not flushed because it didn't get \n
so we thinks that crash occur after debug-point1.
To over come from this, if I disable buffering option with stdio
and stderr
stream like this way
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
Then, is this safe to do this?
Why are all streams by default line buffered ?
Edit :
Usually what is the size of such by default allocated buffer for any file stream? I think it's OS dependent. I would like to know about Linux.
why all stream are by default line buffered
They are buffered for performance reasons. The library tries hard to avoid making the system call because it takes long. And not all of them are buffered by default. For instance stderr
is usually unbuffered and stdout
is line-buffered only when it refers to a tty.
then is this safe to do this?
It is safe to disable buffering but I must say it's not the best debugging technique.