gpt4 book ai didi

c - 如何修复C中的段错误

转载 作者:行者123 更新时间:2023-11-30 20:25:54 26 4
gpt4 key购买 nike

你好,我编写了将在 Linux 上运行的 C 程序。我正在尝试为 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];
}

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

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

最佳答案

您的main签名错误。你想要

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

当然,您应该删除 main 中的 argCountargs 内部声明.

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

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

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

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

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

关于c - 如何修复C中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27331778/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com