Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault question

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?

like image 515
avd Avatar asked Oct 04 '09 03:10

avd


People also ask

How do I find out what is causing my segmentation fault?

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.

How can segmentation fault be resolved?

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.

How can segmentation fault be avoided?

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.

What kind of error is this segmentation fault?

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.


5 Answers

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.

like image 65
Kredns Avatar answered Oct 05 '22 17:10

Kredns


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.

like image 29
pavium Avatar answered Oct 05 '22 15:10

pavium


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.

like image 44
Falaina Avatar answered Oct 05 '22 17:10

Falaina


You can flush the output buffer right after the printf to to ensure that it will occur before a seg fault. Eg. fflush(stdout)

like image 44
kb. Avatar answered Oct 05 '22 15:10

kb.


Random tip: if you're trying to debug segmentation faults, be sure to try valgrind. It makes it much easier!

like image 26
Peter Avatar answered Oct 05 '22 16:10

Peter