#UN3 weird cat command error

I’m stuck on Stage #QP2.

I’ve tried to pass the “Builtin completion (#QP2)” stage from the “Build your own shell” tutorial. It passes the tests for this specific stage, but it shows that my implementation of the previous stage “Append stderr (#UN3)” has issues.

I have tested my implementation of the whole project so far, and reviewed my code numerous times. I tried to replicate the command that causes the problem on your servers, but it does not happen on my machine. Everything works great on my end.

Here are my logs:

[tester::#QP2] Tearing down shell
[tester::#QP2] Running ./your_program.sh
[tester::#QP2] ✓ Received prompt ($ )
[tester::#QP2] Typed "exi"
[tester::#QP2] ✓ Prompt line matches "$ exi"
[tester::#QP2] Pressed "<TAB>" (expecting autocomplete to "exit" followed by a space)
[tester::#QP2] ✓ Prompt line matches "exit "
[your-program] $ exit
[tester::#QP2] Tearing down shell
[tester::#QP2] Test passed.

[tester::#UN3] Running tests for Stage #UN3 (Redirection - Append stderr)
[tester::#UN3] [setup] export PATH=/tmp/blueberry/blueberry/banana:$PATH
[tester::#UN3] Running ./your_program.sh
[your-program] $ ls -1 nonexistent >> /tmp/rat/ant.md
[your-program] ls: nonexistent: No such file or directory
[tester::#UN3] ✓ Received error message
[tester::#UN3] ✓ File: /tmp/rat/ant.md is empty
[your-program] $ ls -1 nonexistent 2>> /tmp/rat/owl.md
[your-program] $ cat /tmp/rat/owl.md
[your-program] ls: nonexistent: No such file or directory
[your-program] cat: n" t1: No such file or directory
[tester::#UN3] ^ Expected prompt ("$ ") but received "cat: n\" t1: No such file or directory"
[your-program] $
[tester::#UN3] Test failed

As you can see it keeps displaying this cat command weird error.

For source code reference: GitHub - iAyman-coder/codecrafters-shell-c · GitHub

Hey @iAyman-coder, there might be a few issues at play, but here’s the first one I noticed:

The tokenize function’s argument extraction loop may read past the end of the buffer:

After the last argument, ptr += strlen(ptr) + 1 lands one past the buffer’s terminating '\0'. The next while (*ptr) then reads that out-of-bounds byte.

For example, with input "cat file.txt" tokenized to "cat\0file.txt\0", after reading file.txt, the pointer advances past the final \0 and the while (*ptr) check reads undefined memory.

Thank you for pointing me towards the problem!!!

I have experienced such problem when I was writing the code for the tokenize function, and I thought that I solved it with the while (*dest) *dest++ = \0;.

After debugging with a lot of printf statements and going through multiple resources, I figured out the problem and I solved it.

If there are anymore problems that you found in my code, I hope that you point me towards them if it is not a trouble for you.

Thank you again and have a nice day!