【问题标题】:How to fix Segmentation fault in C如何修复C中的分段错误
【发布时间】:2014-12-06 12:39:48
【问题描述】:

你好,我写了我的 c 程序,它将在 linux 上运行。 我正在尝试为 linux 制作自己的 shell。 我在下面有以下代码...

#include <limits.h>
#include <libgen.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <ctype.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#define MAX_LINE 80 /* 80 chars per line, per command, should be enough. */

int main(void){
       int i = 0;
       int k = 0;
       int argsCount = 0;
       char inputBuffer[MAX_LINE]; /*buffer to hold command entered */
       int background; /* equals 1 if a command is followed by '&' */
       char *args[MAX_LINE/2 + 1]; /*command line arguments */
       pid_t tpid ;
       pid_t child_pid;
       int child_status;
       char path[PATH_MAX+1];
       char *progpath = strdup(args[0]);
       char *prog = basename(progpath);
       char temp[MAX_LINE];
}

它编译得很好,但是当我尝试运行代码时,它给了我分段错误错误

我该如何解决它以及为什么会出现此错误?

【问题讨论】:

  • 试过初始化args[0](定义)?
  • char *progpath = strdup(args[0]); : args[0] 未初始化。
  • 这里的args[0]是什么
  • 编译所有警告和调试信息 (gcc -Wall -Wextra -g)。然后使用调试器 (gdb)(还有valgrind....)

标签: c linux segmentation-fault


【解决方案1】:

您的main 签名错误。你想要

 int main(int argsCount, char**args) {

当然你应该删除argCountargsinternal声明inside你的main

也许您希望您的 argsargCount 包含您自己的 shell 的已解析参数(但您仍然必须为您的 main 提供良好的签名,通常并且经常
int main(int argc, char**argv) .... 您可能希望您的 shell 像大多数 shell 一样接受 -c 参数,这将简化使用简单测试用例的调试)。然后你应该初始化它们,你应该在循环中读取一些行(可能是getline)。

正如我所评论的,您应该使用所有警告和调试信息进行编译:

gcc -Wall -Wextra -g yoursource.c -o yourprog

然后使用gdb ./yourprog 调试您的程序(参见GDB documentation)。 valgrind 也应该有帮助。当然,一定要在Linux系统上开发!

顺便说一句,你的程序对于 shell 来说并不是一个令人信服的开始。在某些现有 shell 上使用strace 来了解shell 需要做什么。研究一些现有免费软件外壳的源代码(例如sashfishGNU bash ...)。阅读Advanced Linux Programming

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 2015-07-15
    • 2019-03-31
    • 2019-06-20
    • 1970-01-01
    相关资源
    最近更新 更多