I am pretty new to C++. I have a lot of assignments with data structures and every time I try implementing anything related to linked lists such as Trees, Hashtables etc I usually end up with a segmentation error. What precautions are to be taken to avoid these?. By the way, I got my linked list right on the 8th attempt so please note I am a beginner.
Asked
Active
Viewed 160 times
0
-
3Crashes like that are because your program have bugs. You solve the crashes by fixing the bugs. I recommend you take some time to [learn how to debug your programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – Some programmer dude Mar 22 '18 at 07:35
-
There is a common problem for segmentation fault (especially if you are new and work with pointers): Trying to reference via an invalid address. So be sure you don't do it. like accessing address after `free` memory. – Afshin Mar 22 '18 at 07:37
-
That's like asking for best practices of C++ programming, but on that topic, there are whole books, so that's way too wide of a question to answer here. However, take a look at the eight attempts you made. Now, each new iteration fixed some errors. Look at those, try to generalize them and then think about what you could have done to avoid making them in the first place. That's not an advise that is strongly tied to any programming, it's just common (engineers) wisdom. – Ulrich Eckhardt Mar 22 '18 at 07:39
-
As for precautions, the only precaution you could have is to write bug-free code to begin with. Which is almost impossible for any non-trivial program. – Some programmer dude Mar 22 '18 at 07:41
-
Segfaults are actually some of the nicer things that can happen. If you run your program in a debugger, they usually stop when a segfault occurs. This allows you to inspect the current state of the program (the variables) and the back trace so you can see how the program came to its untimely end. – user4581301 Mar 22 '18 at 07:48
-
the only way is learning from mistakes and knowing basics. The only precaution you can take is to handle memory/pointers with utter care. Google and learn why SEGV occurs, this will make you think how not to do a SEGV. – Yogesh Mar 22 '18 at 07:51
-
1A common, because it's effective, recommendation when working with linked data structures is to draw the suckers. Visualize the list. walk through the instructions you gave the computer on paper with a pencil. If you find yourself drawing something stupid, not only have you found a bug, but you probably have a good idea what you need to draw, and code, instead. – user4581301 Mar 22 '18 at 08:04
1 Answers
2
No problem that you are a beginner, first try to build the logic on paper and then in the program.
Segmentation fault mostly caused by invalid pointer access, I faced that too when I was learning Data Structure.
Try to use debugger programs like GDB and Valgrind. These will trace back the error and will tell about memory leak.
Check these out:

Vipin Yadav
- 1,616
- 1
- 14
- 23