Debugging my printf
Yesterday I fixed a lot of bugs on my printf. I’m pretty sure I’ll get it done by Wednesday at the latest.
I learned how to use valgrind and gdb to debug my code:
They’re amazing tools and it’s saving me a lot of time.
You can run them straight from the shell or you can integrate them with your VSCode by following these simple steps:
Create a build task with
Terminal > Configure Default Build Task. This will generate a.vscode/tasks.jsonfile that tells VSCode how to compile your program.Open
.vscode/tasks.jsonand configure the compiler arguments and working directory:
{
...
"args": ["-g", "*.c", "-o", "a.out"],
"options": {
"cwd": "${workspaceFolder}/path/to/sourcefiles"
},
...
}
- Test your build with
Ctrl + Shift + B. It should open a panel at the bottom of your screen with a success or error message. - Create debug task with
Run > Add Configuration > C++ (GDB/LLDB) - Point the
programpath to your executable:
{
...
"program": "${workspaceFolder}/path/to/a.out",
...
}
- Add break points to your code by clicking the red dot on the editor’s gutter.
- Start the debugger with
F5
TIP OF THE DAY: You can run gdb on a coredump file and access the state
of your program before it crashed.
This is super useful while fixing segfault.
Today I’ll continue working on printf.
I’m also starting an Elixir bootcamp from Rocket Seat. Learning functional languages is really helping me organize my C code better:
Since my main language is ruby, I’m used to thinking about my code in classes. This was hindering a lot of my progress in C, since those resources simply don’t exist in that language and I was having a hard time organizing my projects without them.
After I created my first Phoenix app and learned about function modules
everything clicked: I started creating families of functions as my
organizational unit, and separating structs accordingly.
This results in effective control structures for each function that are easily
extendable without the need for classes and objects.
My greatest obstacle was figuring out all the flag combinations that printf handles. It’s very arbitrary how they interact with each-other, and I couldn’t find any tutorials online that explain this well. I figured it out by trail and error, by running a ton of tests and examples.