Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I always get segmentation faults while doing my assignments. Actually I do use debugger to solve them but I want to know how should we avoid them?

Any help will be appreciated.

What I have tried:

I usually try but always waste whole day for that single line of code... :-)
Posted
Updated 12-Jan-17 18:31pm
Comments
Philippe Mori 13-Jan-17 16:04pm    
Write correct code and you would not have segmentation fault. It is as simple as that.

Typical beginner errors that may lead to seg faults are:

Using uninitialised variables (especially for array indexes).
Always initialise variables.

Not checking function return values.
Functions might return special values like a NULL pointer or a negative integer to indicate an error. Or the return values indicates that values passed back by arguments are not valid.
Always check for error states and break execution upon errors.

Looping up to and including the length of an array.
The last element of an array is accessed with length - 1.
Loop end conditions must be < length (not <=).

Improper length for arrays using sizeof.
Don't use sizeof for pointers of dynamically created arrays (it is just the pointer size).
Don't forget to divide by the item size when the items are larger than a byte when determining the length of fixed arrays (use sizeof(array) / sizeof(array[0])).

Changing literal array sizes not at all places.
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.

And probably more. But the above are common and are seen here at CP quite often.

Final tips:
Set the warning level of the compiler to maximum. Some of the above problems like unitialised variables are then detected by the compiler.

Use a static code analyser like Cppcheck - A tool for static C/C++ code analysis[^].
 
Share this answer
 
Careful programming is the way to avoid them. Like any C/C++ programmer, you should master dynamic memory allocation, pointers, and the like.
 
Share this answer
 
Quote:
segmentation faults

This happen typically when your program try to access a place it don't own.
A clever use of debugger will help you to find where is the problem.
We can't help you mire without seeing your code.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900