开发者

Unix shell C code: random errors

I'm coding a UNIX shell in C, and ever since I s开发者_如何学Pythontarted using GNU Readline, I'm having the weirdest errors.

Segmentation faults and SIGABRT signals appear at almost completely random. GDB never shows me the same cause of the problem twice.

I'm posting my code in a pastebin.

Agros.h

Agros.c

Main.c

I guess what I'm asking is if anyone could help me debugging, or at least reviewing parts of my code, I'd be most honored. I'm still new to programming and will appreciate very much any help I can get.

Regards.


I tried to compile your code and the compiler warned me of a dangerous problem:

agros.c: In function ‘return_prompt’:
agros.c:114:5: warning: function returns address of local variable

This is a typical newbie error and it can easily be the reason of random faults you describe. The value of the "prompt" you return will be overwritten by following function call parameters because it resides in your program stack, this could lead to random memory "corruptions".


I notice at least that get_cmd_code() is buggy. I haven't looked deeper into your code so fix this and if you still have problems let me know.

You have code that is iterating over a static array of command elements. You reserve room for the 100 elements in the start of the file (in the array declaration) but you don't actually initialize 100 elements. my_commands[4].command_name is null so passing it to strcmp() will cause a segfault.

Better practice is to define a constant k_command_count and then iterate your loop from 0 to k_command_count - 1. You should also define my_commands as my_commands[ k_command_count ] so you don't waste memory. There are other even better ways of doing things but while you're learning I suggest keeping it simple.


I checked for the common programming error of improperly allocated memory, but everything looks fine.

By any chance, do segfaults only happen when an empty line is input? If so, the logic in parse_command() which detects an empty line is forcing another call of strtok() when it should not. It would be better to skip the while loop completely there, like what should happen if NULL were not revised with `word = ""``

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜