DEV Community

Discussion on: I'm an Expert in Memory Management & Segfaults, Ask Me Anything!

Collapse
 
awesomecrystalcat profile image
Crystal Cat

Hello, Jason!

I'm trying to recreate the ls command, but catch the segmentation fault when trying to print recursively ls -R / command. I'm checking if I have permission to open the folder and it's working pretty nice. Each time it reaches different depth of file tree. Could you, please, give a piece of advice how to handle it and what can cause the segmentation. Thanks in advance!

Collapse
 
codemouse92 profile image
Jason C. McDonald

The first rule of debugging: "If it's weird, it's memory."

You have to remember, a segmentation fault is just a form of undefined behavior. You can use a dynamic analyzer, such as Valgrind, to dial in on the exact part of the your code with the problem.

Look especially for the following "hot spots" for undefined behavior:

  • Dereferencing pointers.
  • Dynamic allocation.
  • Passing by or returning a reference.
  • Traversing array-like structures, such as C-strings.

A while back, I wrote up a big list of common reasons for segmentation faults. It might be helpful.