I have observed that sometimes in C programs, if we have a printf
in code anywhere before a segmentation fault, it does not print. Why is this so?
Check shell limits Usually it is the limit on stack size that causes this kind of problem. To check memory limits, use the ulimit command in bash or ksh , or the limit command in csh or tcsh . Try setting the stacksize higher, and then re-run your program to see if the segfault goes away.
It can be resolved by having a base condition to return from the recursive function. A pointer must point to valid memory before accessing it.
Use a #define or the sizeof operator at all places where the array length is used. Improper handling of NULL terminated strings. Forgetting to allocate space for the terminating NULL character. Forgetting to set the terminating NULL character.
Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you.” It's a helper mechanism that keeps you from corrupting the memory and introducing hard-to-debug memory bugs.
It's because the output from printf()
is buffered. You could add fflush(stdout);
immediately after your printf
and it would print.
Also you could do this:
fprintf(stderr, "error string");
since stderr
is not buffered.
There's also a related question.
If the segmentation fault occurs too soon after a printf, and the output buffer was not flushed, you won't see the effect of the printf.
Most libc implementations buffer printf output. It's usually sufficient to append newline (\n) to the output string to force it to flush the buffers contents.
You can flush the output buffer right after the printf to to ensure that it will occur before a seg fault. Eg. fflush(stdout)
Random tip: if you're trying to debug segmentation faults, be sure to try valgrind. It makes it much easier!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With